0

What my requirement is "I have an application that downloads images from the amazon s3 bucket. And I need to cache those images, I used normal cache for doing it. But I need to implement the cache technique same as that of SDWebImage". How the caching method in SDWebImage works.

  • Why you are not using `SDWebImage`. Why you want to build your own while `SDWebImage` has a good reputation on this? – Torongo Dec 19 '18 at 08:09

2 Answers2

2

create a cache and set image to the url string and assign it from anywhere by checking the cache have the object or not

  let imageCache = NSCache<AnyObject, AnyObject>()

  imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)

  if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
     self.image = imageFromCache
     return
  }
Torongo
  • 1,021
  • 1
  • 7
  • 14
0

Pretty Handy UIImageview Extension for image caching.

import UIKit

let imageCache = NSCache<AnyObject, AnyObject()

extension UIImageView {
  func cacheImage(urlString: String){
    let url = URL(string: urlString)

    image = nil

    if let imageFromCache = imageCache.object(forKey: urlString as AnyObject) as? UIImage {
        self.image = imageFromCache
        return
    }

    URLSession.shared.dataTask(with: url!) {
        data, response, error in
          if let response = data {
              DispatchQueue.main.async {
                  let imageToCache = UIImage(data: data!)
                  imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)
                  self.image = imageToCache
              }
          }
     }.resume()
  }
}
Vinaykrishnan
  • 740
  • 3
  • 14
  • 34