Caching

How to customize cache layers

The default Nuke configuration has a memory cache and an HTTP disk cache1 enabled. You can also enable custom disk cache if needed (faster and ignores HTTP cache-control headers). It can store either original or processed images (or both).

LRU Memory Cache #

Nuke’s default ImagePipeline has two cache layers. The first layer is the memory cache storing processed images that are ready to be displayed.

// Configure cache
ImageCache.shared.costLimit = 1024 * 1024 * 100 // 100 MB
ImageCache.shared.countLimit = 100
ImageCache.shared.ttl = 120 // Invalidate image after 120 sec

// Read and write images
let request = ImageRequest(url: url)
ImageCache.shared[request] = ImageContainer(image: image)
let image = ImageCache.shared[request]

// Clear cache
ImageCache.shared.removeAll()

ImageCache uses the LRU algorithm – the least recently used entries are removed first.

HTTP Disk Cache #

By default, unprocessed image data is stored using URLCache.

// Configure cache
DataLoader.sharedUrlCache.diskCapacity = 100
DataLoader.sharedUrlCache.memoryCapacity = 0

// Read and write responses
let request = ImageRequest(url: url)
let _ = DataLoader.sharedUrlCache.cachedResponse(for: request.urlRequest)
DataLoader.sharedUrlCache.removeCachedResponse(for: request.urlRequest)

// Clear cache
DataLoader.sharedUrlCache.removeAllCachedResponses()

See “Image Caching” to learn more about HTTP cache.

Aggressive Disk Cache #

If HTTP caching is not your cup of tea, try a custom LRU disk cache for fast and reliable aggressive data caching (ignores HTTP cache control). You can enable it using the pipeline configuration.

ImagePipeline {
    $0.dataCache = try? DataCache(name: "com.myapp.datacache")
}

If you enable aggressive disk cache, make sure to disable the native URL cache. To do it, pass a DataLoader with a custom URLSessionConfiguration when creating a pipeline. To learn more about the configuration, see “Image Pipeline”.

By default, the pipeline stores only the original image data. To store processed images instead, set dataCacheOptions.storedItems to [.finalImage]. You can use this option if the app applies heavy processors or downsamples images to save space.

To save disk space see ImageEncoders.ImageIO and ImageEncoder.isHEIFPreferred option for HEIF support.

Reloading Images #

Use image pipeline to remove the image from all cache layers.

let request = ImageRequest(url: url)
pipeline.removeCachedImage(for: request)

If you want to keep the image in caches but reload it, you can instruct the pipeline to ignore the cached data.

let request = ImageRequest(url: url, cachePolicy: .reloadIgnoringCacheData)
Nuke.loadImage(with: request, into: imageView)

If you are manually constucting a URLRequest, make sure to update the respective cache policy too.

  1. Nuke 10 will use custom disk cache by default.