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.