An object that maps URL requests to cached response objects.
SDKs
- iOS 2.0+
- macOS 10.2+
- UIKit for Mac 13.0+Beta
- tvOS 9.0+
- watchOS 2.0+
Framework
- Foundation
Declaration
class URLCache : NSObject
Overview
The URLCache
class implements the caching of responses to URL load requests by mapping NSURLRequest
objects to Cached
objects. It provides a composite in-memory and on-disk cache, and lets you manipulate the sizes of both the in-memory and on-disk portions. You can also control the path where cache data is stored persistently.
Note
In iOS, the on-disk cache may be purged when the system runs low on disk space, but only when your app is not running.
Thread Safety
In iOS 8 and later, and macOS 10.10 and later, URLCache
is thread safe.
Although URLCache
instance methods can safely be called from multiple execution contexts at the same time, be aware that methods like cached
and store
have an unavoidable race condition when attempting to read or write responses for the same request.
Subclasses of URLCache
must implement overridden methods in such a thread safe manner.
Subclassing Notes
The URLCache
class is meant to be used as-is, but you can subclass it if you have specific needs. For example, you might want to screen which responses are cached, or reimplement the storage mechanism for security or other reasons.
When overriding methods of this class, be aware that methods that take a task
parameter are preferred by the system to those that do not. Therefore, you should override the task-based methods when subclassing, as follows:
Storing responses in the cache — Override the task-based
store
, instead of or in addition to the request-basedCached Response(_: for:) store
.Cached Response(_: for:) Getting responses from the cache — Override
get
, instead of or in addition toCached Response(for: completion Handler:) cached
.Response(for:) Removing cached responses — Override the task-based
remove
, instead of or in addition to the request-basedCached Response(for:) remove
.Cached Response(for:)