AlamofireImage 磁盘缓存不工作

AlamofireImage Disk Cache not working

我想使用 AlamofireImage 从 url 下载图像,然后将其缓存到设备磁盘 space。我阅读了几篇关于此的文章,发现 AlamofireImage 在 ImageDownloader class. The most interesting information was given in this SO answer

的帮助下支持这一点

所以我尝试为 ImageDownloader 设置一个自定义的 NSURLCache,以便它将图像直接缓存到磁盘。我通过将内存容量设置为 0 来做到这一点。然后我使用这个自定义 ImageDownloader 下载图像。我为磁盘路径指定的文件夹是在磁盘上创建的,但不幸的是它仍然是空的,并且图像没有以任何方式缓存。

** 编辑:** 请务必注意,缓存的响应并未保存在缓存目录中的文件夹中,而是保存在该文件夹旁边的数据库文件中。

谁能告诉我我做错了什么?非常感谢阅读!

func diskImageDownloader(diskSpaceMB: Int = 100) -> ImageDownloader {

    let diskCapacity = diskSpaceMB * 1024 * 1024
    let diskCache = NSURLCache(memoryCapacity: 0, diskCapacity: diskCapacity, diskPath: "alamofireimage_disk_cache")
    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.URLCache = diskCache
    let downloader = ImageDownloader(configuration: configuration)
    UIImageView.af_sharedImageDownloader = downloader

    return downloader
}

func getProfileImage(atURL url: String, onComplete: SRServiceResponse<UIImage> -> Void) {
    guard let imageURL = NSURL(string: url) else
    {
        // TODO: Fail here
        return
    }

    let request = NSURLRequest(URL: imageURL)

    let imageDownloader = self.diskImageDownloader()

    imageDownloader.downloadImage(URLRequest: request) { (response) in
        switch response.result
        {
        case .Success(let image):
            // Do something
        case .Failure(let error):
            // Do something
        }
    }
}

为了实现您的目标,请将用作磁盘缓存的 NSURLCache 真正自定义为存储的图像设置您自己的到期日期:

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)
    }
}

不必每次都创建一个新的 ImageDownloader,您可以重用共享实例来调用 downloadImage 方法:UIImageView.af_sharedImageDownloader.downloadImage(URLRequest: request)

我这样做不是为了代表。只是为了节省您使用编译器的时间。

Swift3.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)
  }
}