我想使用AlamofireImage从URL下载图像并将其缓存到设备磁盘空间中。我阅读了几篇关于此问题的文章,并发现AlamofireImage通过ImageDownloader类来支持此功能。最有趣的信息在这个SO答案中提供。
因此,我尝试为ImageDownloader设置自定义的NSURLCache,以便直接将图像缓存到磁盘中。我通过将内存容量设置为0来实现这一点。然后,我使用这个自定义的ImageDownloader来下载图片。我指定的磁盘路径的文件夹已经在磁盘上创建了,但不幸的是它一直是空的,图像没有以任何方式被缓存。
**编辑:** 需要注意的是,缓存响应并未保存在缓存目录中的文件夹中,而是保存在该文件夹旁边的一个数据库文件中。
请问有人能告诉我我在这里做错了什么吗?非常感谢您的阅读!
因此,我尝试为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
}
}
}