AlamofireImage Disk Cache not working

柔情痞子 提交于 2019-12-04 04:15:42

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)

I'm not doing this for rep. Just to save you time with the compiler.

In Swift 3.0

class DiskCache: URLCache {


  private let constSecondsToKeepOnDisk = numDaysToKeep*24*60*60 // numDaysToKeep is your own constant or hard-coded value

  override func storeCachedResponse(_ cachedResponse: CachedURLResponse, for request: URLRequest) {

    var customCachedResponse = cachedResponse
    // Set custom Cache-Control for Image-Response
    let response = cachedResponse.response as! HTTPURLResponse

    if let contentType = response.allHeaderFields["Content-Type"] as? String,
        var newHeaders = response.allHeaderFields as? [String: String], contentType.contains("image") {
        newHeaders["Cache-Control"] = "public, max-age=\(constSecondsToKeepOnDisk)"
        if let url = response.url, let newResponse = HTTPURLResponse(url: url, statusCode: response.statusCode, httpVersion: "HTTP/1.1", headerFields: newHeaders) {
            customCachedResponse = CachedURLResponse(response: newResponse, data: cachedResponse.data, userInfo: cachedResponse.userInfo, storagePolicy: cachedResponse.storagePolicy)
        }
    }
    super.storeCachedResponse(customCachedResponse, for: request)
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!