I need to cache images on disk but to limit them say to 20 images. I am trying Nuke
library. When I run
Nuke.loadImage(with: url, options: options, into: imageView)
image is cached as long as I am inside my View Controller. When I leave the views, next time images are being fetched again. So how do I make Nuke
(or other lib) save those images for specific image count or time.
Before trying Nuke
I was just saving images to Documents folder of the app every time I fetch image. I am sure there is a better way.
Update: I was able to do it with Kingfisher
.
func getFromCache(id: String) {
ImageCache.default.retrieveImage(forKey: id, options: nil) {
image, cacheType in
if let image = image {
self.galleryImageView.image = image
} else {
print("Not exist in cache.")
self.loadImage()
}
}
}
private func loadImage() {
ImageDownloader.default.downloadImage(with: url, options: [], progressBlock: nil) {
(image, error, url, data) in
if let image = image {
self.galleryImageView.image = image
ImageCache.default.store(image, forKey: id, toDisk: true)
}
}
}
If I understand correctly, first retrieveImage
fetches images from disk cache. Later from memory cache. And it frees them only when memory warning received. I hope it does. God help us.