ios – 如果存在于Alamofire图像中,则使用磁盘缓存图像

我正在使用AlamofireImage库来缓存下载的图像.

码:

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

日志:

enter image description here

日志显示请求第一个图像,第二个图像从缓存中获取.没有额外的请求,图像立即显示.

我希望当我重新启动应用程序时,即使是从缓存中获取的第一张图像,但Log仍保持不变.我查看了Library / Caches /…/ fsCachedData,图像就在那里,准备好了.

题:
我在这里失踪了什么?我需要在后续请求中从磁盘缓存中获取第一个图像.

最佳答案
这种方法将映像请求保存在磁盘上,因为它们的缓存控制最大使用时间和空间可用.如果要设置自己的最大年龄,则必须将custom NSURLCache设置为diskCache,您必须在storeCachedResponse方法中返回修改后的cachedResponse.顺便说一下,内存缓存由ImageDownloader中的AutoPurgingImageCache处理.
使用此方法设置下载程序:

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

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

更新于08/09/16,了解@ kishorer747:

NSURLCache memoryCapacity为零,因为我不希望将图像请求响应保存在缓存中以节省内存.应该只有内存中的AutoPurgingImageCache将请求URL保存为关键图像.您可以修改我的示例方法,为图像内存缓存设置所需的cacheCapacity和cachePurgeCapacity:

let cacheCapacity = 100 * 1024 * 1024
let cachePurgeCapacity = 60 * 1024 * 1024
let imageCache: ImageRequestCache = AutoPurgingImageCache(memoryCapacity: cacheCapacity, preferredMemoryUsageAfterPurge: cachePurgeCapacity)
let downloader = ImageDownloader(configuration: configuration, imageCache: imageCache)

转载注明原文:ios – 如果存在于Alamofire图像中,则使用磁盘缓存图像 - 代码日志