10

我正在使用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
            }
        }
    }
}

日志:

在此处输入图像描述

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

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

问题: 我在这里缺少什么?我需要在后续请求中从磁盘缓存中获取第一张图像。

4

1 回答 1

11

这种方法将图像请求保存在磁盘上,只要它们的缓存控制最大年龄表示并且空间可用。如果要设置自己的最大年龄,则必须设置自定义 NSURLCache作为diskCache您必须cachedResponsestoreCachedResponse方法中返回修改的位置。顺便说一句,内存缓存AutoPurgingImageCacheImageDownloader. downloader使用此方法设置您的:

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
    }

@kishorer747 于 08/09/16 更新:

NSURLCache为零 memoryCapacity,因为我不希望将图像请求响应保存在缓存中以节省内存。内存中应该只保存请求 url 的图像作为键AutoPurgingImageCache。您可以按如下方式修改我的示例方法以设置所需cacheCapacitycachePurgeCapacity图像内存缓存:

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)
于 2016-07-27T19:28:17.360 回答