1

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)

        }
  • I dont know exactly what your problem is. But about caching images, you can check a framework named Kingfisher https://github.com/onevcat/Kingfisher – Quang Hà Sep 26 '16 at 01:25
  • my problem is cache is automatically deleted when I press home button then go back to my app – Khôi V Nguyễn Sep 26 '16 at 01:26
  • are your images cached on memory? – Quang Hà Sep 26 '16 at 01:29
  • I use static var cache = NSCache(), then I set object ProfileVC.cache.setObject(img, forKey: self.image.imageUrl as NSString), 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) } – Khôi V Nguyễn Sep 26 '16 at 01:42
  • I updated the question :D – Khôi V Nguyễn Sep 26 '16 at 01:44

0 Answers0