使用磁盘缓存图像(如果存在于Alamofire图像中)

时间:2016-05-04 23:35:57

标签: ios swift alamofire alamofireimage

我使用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,图像就在那里,准备好了。

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

1 个答案:

答案 0 :(得分:10)

此方法将映像请求保存在磁盘上,因为它们的缓存控制最大使用时间和空间可用。如果您想设置自己的最长年龄,则必须将custom NSURLCache设置为diskCache,您必须在storeCachedResponse中返回修改后的cachedResponse方法。顺便说一下,内存缓存由AutoPurgingImageCache中的ImageDownloader处理。 使用以下方法设置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
    }

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

NSURLCache memoryCapacity为零,因为我不希望将图像请求响应保存在缓存中以节省内存。应该只有内存中的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)