我使用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
,图像就在那里,准备好了。
问题: 我在这里失踪了什么?我需要在后续请求中从磁盘缓存中获取第一个图像。
答案 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
将请求网址保存为关键字的图像。您可以修改我的示例方法,为图像内存缓存设置所需的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)