An object that maps URL requests to cached response objects.


The URLCache class implements the caching of responses to URL load requests by mapping NSURLRequest objects to CachedURLResponse 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.

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 cachedResponse(for:) and storeCachedResponse(_:for:) 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.


Getting and setting shared cache

class var shared: URLCache

Returns the shared NSURLCache instance.

Creating a new cache object

init(memoryCapacity: Int, diskCapacity: Int, diskPath: String?)

Initializes an NSURLCache object with the specified values.

Removing cached objects

func removeCachedResponse(for: URLRequest)

Removes the cached URL response for a specified URL request.

func removeAllCachedResponses()

Clears the receiver’s cache, removing all stored cached URL responses.

Getting and setting on-disk cache properties

var currentDiskUsage: Int

The current size of the receiver’s on-disk cache, in bytes.

var diskCapacity: Int

The capacity of the receiver’s on-disk cache, in bytes.

Getting and setting in-memory cache properties

var currentMemoryUsage: Int

The current size of the receiver’s in-memory cache, in bytes.

var memoryCapacity: Int

The capacity of the receiver’s in-memory cache, in bytes.

Cache Storage Policies

enum URLCache.StoragePolicy

These constants specify the caching strategy used by an NSCachedURLResponse object.


Inherits From

Conforms To

See Also

Cache Behavior

Accessing Cached Data

Control how URL requests make use of previously cached data.

class CachedURLResponse

A cached response to a URL request.