how can I cache an image in swift 5?

2.9k Views Asked by At

I am having trouble finding a good example of how I can cache images in a table view using URLSession to get image from the internet (API).

However, I am getting issues with the cache - Here is my code so far:

func configure(with urlString: String, name: String, address: String, station: String) {
    
    var imageCache = NSCache<UIImage, String>()
    
    loader.startAnimating()
    loader.isHidden = false
    
    guard let url = URL(string: urlString) else {
        return
    }
    
    let task = URLSession.shared.dataTask(with: url) { [weak self] data, _, error in
        guard let data = data, error == nil else {
            return
        }
        
        let locationImage = UIImage(data: data)
        
        imageCache.setObject(locationImage!, forKey: urlString)
        
        imageCache[url] = locationImage
        
        DispatchQueue.main.async {
            self?.nameLabel.text = name
            self?.addressLabel.text = address
            self?.locationImageView.image = locationImage
            self?.loader.stopAnimating()
            self?.loader.isHidden = true
        }
    }
    task.resume()
}

screnshot of code

errors include:

Cannot convert value of type 'String' to expected argument type 'UIImage' Value of type 'NSCache<UIImage, AnyObject>' has no subscripts 'NSCache' requires that 'String' be a class type

1

There are 1 best solutions below

2
Vadim Belyaev On

The statement

var imageCache = NSCache<UIImage, String>()

creates a cache where the key type is UIImage and the objects stored in the cache are Strings. You want it to be the other way round with one caveat: NSCache doesn't support String for the key type, it has to be NSString:

var imageCache = NSCache<NSString, UIImage>()

That way you'll be able to put UIImages into the cache while identifying them by URL strings.

Check out my demo project on GitHub: https://github.com/vadimbelyaev/ImagesCache