Alamofireimage Disk Cache Not Working

AlamofireImage Disk Cache not working

To reach your goal make your NSURLCache which you use as diskCache really custom to set your own expiration date for the stored images:

class DiskCache: NSURLCache {
private let constSecondsToKeepOnDisk = 30*24*60*60 // 30 days

override func storeCachedResponse(cachedResponse: NSCachedURLResponse, forRequest request: NSURLRequest) {
var customCachedResponse = cachedResponse
// Set custom Cache-Control for Image-Response
if let response = cachedResponse.response as? NSHTTPURLResponse,
let contentType = response.allHeaderFields["Content-Type"] as? String,
var newHeaders = response.allHeaderFields as? [String: String] where contentType.containsString("image") {
newHeaders["Cache-Control"] = "public, max-age=\(constSecondsToKeepOnDisk)"
if let url = response.URL, newResponse = NSHTTPURLResponse(URL: url, statusCode: response.statusCode, HTTPVersion: "HTTP/1.1", headerFields: newHeaders) {
customCachedResponse = NSCachedURLResponse(response: newResponse, data: cachedResponse.data, userInfo: cachedResponse.userInfo, storagePolicy: cachedResponse.storagePolicy)
}
}
super.storeCachedResponse(customCachedResponse, forRequest: request)
}
}

Instead of creating a new ImageDownloader every time you could reuse the shared instance to call the downloadImage method: UIImageView.af_sharedImageDownloader.downloadImage(URLRequest: request)

How is Alamofireimage saving the image to disk cache?

It is possible to save the response for the image request on disk. You can init the ImageDownloader with a modified configuration with your desired NSURLCache and set it also as the UIImageView.af_sharedImageDownloader. Here I've posted an example method for that.

Refresh cached image in AlamofireImage?

Looks like none of available pods are able to refresh cached images, or any other cached content, when the content is changed on server. It is technically possible due to Content-Control technology, but apple does not seem to provide this possibility https://developer.apple.com/documentation/foundation/nsurlrequest.cachepolicy/1414422-reloadrevalidatingcachedata

reloadRevalidatingCacheData
Specifies that the existing cache data may
be used provided the origin source confirms its validity, otherwise
the URL is loaded from the origin source.
This constant is unimplemented and shouldn’t be used.

Your best move would be to ask server developer to generate unique URL addresses to any image that will change(avatar, backgrounds, icons etc), or if server developer is not available you should just get rid of the caching in places where there is such a problem and use casual download.

In any case you can use my gist for downloading images cached and not cached here https://gist.github.com/sam-moshenko/562ec61431c4a0ebeb68899b4d1b4d26 (Just don't forget to install pod 'AlamofireImage')



Related Topics



Leave a reply



Submit