I'm using the AlamofireImage library to cache downloaded images.
Code:
import UIKit
import AlamofireImage
class ViewController: UIViewController {
@IBOutlet weak var firstImageView: UIImageView!
@IBOutlet weak var secondImageView: UIImageView!
let downloader = ImageDownloader()
let URLRequest = NSURLRequest(URL: NSURL(string: "https://httpbin.org/image/jpeg")!)
override func viewDidLoad() {
super.viewDidLoad()
requestFirstImage()
}
func requestFirstImage() {
downloader.downloadImage(URLRequest: URLRequest) { response in
print(response.request)
print(response.response)
debugPrint(response.result)
if let image = response.result.value {
self.firstImageView.image = image
self.requestSecondImage()
}
}
}
func requestSecondImage() {
downloader.downloadImage(URLRequest: URLRequest) { response in
print(response.request)
print(response.response)
debugPrint(response.result)
if let image = response.result.value {
self.secondImageView.image = image
}
}
}
}
Log:
As the log shows the first image is requested and the second one is fetched from the cache. No extra request is made and the image shows instantly.
I expect when i re-launch the app that even the first image where fetched from the cache but the Log
remains the same. I looked to the Library/Caches/.../fsCachedData
and the image is there, ready to be fetched.
Question: What i'm missing here ? I need that the first image get fetched from the disk cache on subsequent requests.
This approach saves the image requests as long on the disk as their cache control max age says and space is available. If you want to set an own max age you have to set up a custom NSURLCache as
diskCache
where you have to return your modifiedcachedResponse
in the storeCachedResponse method. By the way, the memory cache is handled by theAutoPurgingImageCache
in theImageDownloader
. Set up yourdownloader
with this method:Updated on 08/09/16 for @kishorer747:
The NSURLCache
memoryCapacity
is zero because I don't want image request responses to be saved in cache to save memory. There should only the image be saved for the request url as key by theAutoPurgingImageCache
in memory. You can modify my example method as followed to set your desiredcacheCapacity
andcachePurgeCapacity
for the image memory cache: