title: Image Caching – How to control when images are disposed?
body: <p>I need to cache images on disk but to limit them say to 20 images. I am trying <code>Nuke</code> library. When I run</p>
  
  <pre><code>Nuke.loadImage(with: url, options: options, into: imageView)
  </code></pre>
  
  <p>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 <code>Nuke</code> (or other lib) save those images for specific image count or time. </p>
  
  <p>Before trying <code>Nuke</code> I was just saving images to Documents folder of the app every time I fetch image. I am sure there is a better way.</p>
  
  <p>Update: I was able to do it with <code>Kingfisher</code>.</p>
  
  <pre><code>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)
          }
      }
  }
  </code></pre>
  
  <p>If I understand correctly, first <code>retrieveImage</code> 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.</p>