URLSession Cache Policy
Also known as: urlsession cache policy, ios request cache, ios urlsession cache policy
URLSession cache policy controls whether an iOS network request reuses a stored HTTP response or revalidates with the server. It is set via URLRequest.cachePolicy and backed by URLCache, which holds responses in memory and on disk.
- Set per-request behavior with URLRequest.cachePolicy; .useProtocolCachePolicy (the default) obeys HTTP response headers.
- Cached responses are stored by URLCache in memory and on disk, with capacities you set via memoryCapacity/diskCapacity.
- The disk cache counts toward the app's storage and is cleared with URLCache.removeAllCachedResponses().
How the policy is chosen
Each request carries a cachePolicy of type URLRequest.CachePolicy. The default, .useProtocolCachePolicy, follows the HTTP caching rules in the response headers (`Cache-Control`, `Expires`, `Etag`). Other values let you override that: .reloadIgnoringLocalCacheData always hits the network, while .returnCacheDataElseLoad and .returnCacheDataDontLoad prefer or require the stored copy — useful for offline reads.
Storage is handled by URLCache, shared by default through URLCache.shared. A response only becomes cacheable when the protocol allows it (typically a GET over HTTP/HTTPS with appropriate headers) and it fits within the cache's memory and disk capacity limits. You can also intercept and rewrite caching per response with the session delegate method urlSession(_:dataTask:willCacheResponse:completionHandler:).
Why the cache grows
The on-disk portion of URLCache lives inside the app's container and counts against the app's storage footprint — often surfacing as part of an app's 'Documents & Data' in Settings > General > iPhone Storage. A chatty app that caches large GET responses can accumulate tens or hundreds of megabytes here.
To bound it, configure capacities on a custom URLCache(memoryCapacity:diskCapacity:directory:) and assign it to your URLSessionConfiguration.urlCache. Call URLCache.shared.removeAllCachedResponses() (or per-request removal) to clear it. Setting a configuration's requestCachePolicy applies a default policy to every request in that session.