Control how URL requests make use of previously cached data.
The URL Loading System caches responses both in memory and on disk, improving performance and reducing network traffic.
URLCache class is used for caching responses from network resources. Your app can directly access the shared cache instance by using the
shared property of
URLCache. Or, you can create your own caches for different purposes, setting distinct caches on your
Set a Cache Policy for URL Requests
The behaviors of the various policies are described in Table 1. This table shows the policies’ respective preferences for loading from cache or from the originating source, like a server or the local file system. Currently, only HTTP and HTTPS responses are cached. For FTP and file URLs, the only effect of a policy is to determine whether the request is allowed to access the originating source.
Accessed only if needed
Depends on protocol
Depends on protocol
For an explanation of how
use is implemented for HTTP and HTTPS, see
use is the default value for a
Access the Cache Directly
To look for the cached response to a given request, call
cached on the cache. If cached data exists for the request, this call returns a
Cached object; otherwise, it returns
You can inspect resources used by the cache. The properties
disk represent the file system resources used by the cache, and
memory represent memory use.
You can remove cached data for individual items with
remove. You can also clear out many cached items simultaneously with
remove, which removes cached items past a given date, or
remove, which wipes the entire cache.
Manage Caching Programmatically
You can write to the cache programmatically, with the
store method, passing in a new
Cached object and a
Typically, you manage the caching of a response while it’s being handled by a
URLSession object. To manage caching on a per-response basis, implement the
url method of the
URLSession protocol. Note that this delegate method is called only for uploads and data tasks, and is not called for sessions with a background or ephemeral configuration.
The delegate receives two parameters: a
Cached object and a completion handler. Your delegate must call this completion handler directly, passing in one of the following:
Cachedobject, to cache the proposed response as-is
nil, to prevent caching
Listing 1 shows an implementation of
url, which intercepts responses to HTTPS requests and allows the responses to be stored in the in-memory cache only.