Nscache


My notes on NSCache

We fetch the image from cache if it has already been downloaded before:

Or else we download it from remote.

import UIKit
let imageCache = NSCache<NSString, UIImage>()

static func downloadImage(url: URL, completion: @escaping (_ image: UIImage?, _ error: Error? ) -> Void) {
        if let cachedImage = imageCache.object(forKey: url.absoluteString as NSString) {
            completion(cachedImage, nil)
        } else {
            MTAPIClient.downloadData(url: url) { data, response, error in
                if let error = error {
                    completion(nil, error)

                } else if let data = data, let image = UIImage(data: data) {
                    imageCache.setObject(image, forKey: url.absoluteString as NSString)
                    completion(image, nil)
                } else {
                    completion(nil, NSError.generalParsingError(domain: url.absoluteString))
                }
            }
        }
    }

We can also store images in a temp folder and reuse images even after app restarts.

Use apples built in Image caching:

NSURLCache uses both in-memory and on-disk image caching, and it makes its decisions based on the size of the data. All you need to do is to initialise this cache and to set it as a default for your application, and then use NSURLSession to download your images/data.

// You should initialise the cache once your application launches.
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
    let URLCache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
    NSURLCache.setSharedURLCache(URLCache)

    return true
}