1

I'm currently developing an iOS application where I've a lot of images. I use NSCache() for storing the images.

So, every time I load the application the images is being downloaded, saved in cache and stays in the cache all the way till I terminate the application.

I'm looking for a solution where the images will be saved even if you terminate the application, just download if the image does NOT exists in the current NSCache().

This one is used in the beginning of the extension:

let imageCache = NSCache<AnyObject, AnyObject>()

And then I've an extension with a function like this:

extension UIImageView {
func downloadImages(from urlString: NSString){

    //Check for cached images and return out if found
    if let cachedImage = imageCache.object(forKey: urlString) as? UIImage{
        print("cache?", imageCache)
        self.image = cachedImage
        return
    }

    //Retrieve the images from Firebase Storage
    let url = URL(string: urlString as String)

    //Create an URL session
    URLSession.shared.dataTask(with: url!) { (data, response, err) in
        if let err = err{
            print(err.localizedDescription)
        }

        //Continue on background thread
        DispatchQueue.main.async {
            //Check if image exists
            if let downloadedImage = UIImage(data: data!){

                //Add image to cache
                imageCache.setObject(downloadedImage, forKey: urlString)

                //Set the image to downloaded image.
                self.image = downloadedImage
            }
        }
    }.resume()
}

}

The image cache works until I terminate the application. Is there any way I can save the NSCache() even if I terminate the app?

Putte
  • 526
  • 1
  • 6
  • 15

0 Answers0