I use cache to store all the image i have downloaded in collectionView, when I still using the app, it works well. When I press home button, it goes off to home screen, when I go back to the App, it begins downloading again all the image, I wrote the code to check if cachedImg is nil and It's it nil. It means when I leave the app, the app is still running in background, cache is deleted automatically. I want keep that cache until the app has been killed. If any one have any idea, pls help me. Thank you very much !!!
I use
static var cache = NSCache<NSString, UIImage>()
, then I set object
func configureCell(gallery: Gallery, img: UIImage? = nil) {
self.image = gallery
if img != nil {
self.OriginImage.image = img
} else {
DispatchQueue.main.async {
let ref = DataService.instance.OriginImageStorageRef.storage.reference(forURL: self.image.imageUrl)
ref.data(withMaxSize: 2 * 1024 * 1024, completion: { (data, err) in
if err != nil {
print("Unable to download from Storage")
} else {
if let imgData = data {
if let img = UIImage(data: imgData) {
ProfileVC.cache.setObject(img, forKey: self.image.imageUrl as NSString)
self.OriginImage.image = img
}
}
}
})
}
}
}
and call it in ViewCollection,
if let img = ProfileVC.cache.object(forKey: image.imageUrl as NSString) {
cell.configureCell(gallery: image, img: img)
//CachedImg.append(img)
} else {
cell.configureCell(gallery: image)
}