我想使用AlamofireImage从网址下载图片,然后将其缓存在设备磁盘空间中。我阅读了几篇关于此的帖子,发现AlamofireImage在ImageDownloader类的帮助下支持这一点。最有趣的信息是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
}
}
}
答案 0 :(得分:5)
我没有为代表这样做。只是为了节省编译时间。
在 Swift 3.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)
}
}
答案 1 :(得分:4)
要实现您的目标,请将您用作diskCache的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)