0

I am downloading some images and save them in my cache. So far so good, but when quit my app and relaunch it, the cache seems to be empty. I do not know how to check if the cache is actually empty which is why I am asking if the cache gets automatically emptied when the app was force quitted.

let cache = NSCache<NSString, UIImage>() // cache for the downloaded images

JPJerry5
  • 107
  • 10

2 Answers2

3

Yes it does that, for some reason it instantly removes data from cache when app enters background even if there is no memory pressure. To fix this you have to tell NSCache that your data should not be discarded.

What you could do is something like:

class ImageCache: NSObject , NSDiscardableContent {

    public var image: UIImage!

    func beginContentAccess() -> Bool {
        return true
    }

    func endContentAccess() {

    }

    func discardContentIfPossible() {

    }

    func isContentDiscarded() -> Bool {
        return false
    }
}

and then use this class in NSCache like the following:

let cache = NSCache<NSString, ImageCache>()

After that you have to set the data which you cached earlier:

let cacheImage = ImageCache()
cacheImage.image = imageDownloaded
self.cache.setObject(cacheImage, forKey: "yourCustomKey" as NSString)

And finally retrieve the data:

if let cachedVersion = cache.object(forKey: "yourCustomKey") {
     youImageView.image = cachedVersion.image
}

UPDATE

This was already answered by Sharjeel Ahmad. See this link for reference.

Preefix
  • 243
  • 2
  • 13
  • Sounds very good. I will try it later and let you know if it worked for me. Thank you! – JPJerry5 Jun 25 '20 at 10:34
  • I hope it works you. It did for me. – Preefix Jun 25 '20 at 10:41
  • 1
    This looks like a verbatim copy from https://stackoverflow.com/a/52259000, without attribution. Please have a look at [How to reference material written by others](https://stackoverflow.com/help/referencing). – Martin R Jun 25 '20 at 11:07
  • @MartinR my bad! I didn't mean to copy it. I implemented it myself based on his answer. Updated – Preefix Jun 26 '20 at 06:55
  • Okay this works when the app enters the background but not when the app is completely killed. Is there a way to recall the images without downloading after that as well? – JPJerry5 Jun 26 '20 at 15:51
2

NSCache does not persist its elements to the disk. It only keeps them in memory. When an app is force quit then all its RAM is destroyed and obviously cannot be reused at the next launch

Andrey Chernukha
  • 21,488
  • 17
  • 97
  • 161