AFNetworking 是否可以在磁盘上缓存图像超过 session 时间?例如一周或一个月。在我的项目中,我使用了 SDWebImage 和 AFNetworking,但几天前我发现 AFNetworking 与 SDWebImage 具有相同的功能>,所以删除了 SDWebImage 并编写了这样的代码来将图像存储在磁盘上:
对于 ImageView
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:60];
[imageView setImageWithURLRequest:imageRequest placeholderImage:placeholderImage success:nil failure:nil];
下载图片以备将来使用
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:60];
[[AFImageDownloader defaultInstance] downloadImageForURLRequest:imageRequest success:nil failure:nil];
获取下载的图片
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:60];
UIImage *image = [[AFImageDownloader defaultInstance].imageCache imageforRequest:imageRequest withAdditionalIdentifier:nil];
但所有这些仅在每个 session 中有效,在我加载所有图像后我关闭互联网并重新启动我的应用程序,结果 - 缓存中没有图像。
我也尝试在 AppDelegate
中添加这样的代码:
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:2 * 1024 * 1024
diskCapacity:100 * 1024 * 1024
diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
但我仍然无法缓存图像超过 session 时间。 (对不起我的英语)
最佳答案
图像使用 iOS 中内置的标准 NSURLCache 缓存在磁盘上,这意味着如果您的响应包含正确的缓存 header ,那么这些项目最终应该在缓存中的磁盘上。因此,例如 header 应如下所示:
"Accept-Ranges" = bytes;
"Cache-Control" = "max-age=604800";
Connection = close;
"Content-Length" = 3808;
"Content-Type" = "image/png";
Date = "Tue, 29 Mar 2016 19:55:52 GMT";
Etag = "\"5630989d-ee0\"";
Expires = "Tue, 05 Apr 2016 19:55:52 GMT";
"Last-Modified" = "Wed, 28 Oct 2015 09:42:53 GMT";
Server = nginx;
另外,如果您已经下载了图像并想从磁盘缓存中获取它,请执行以下操作:
NSURLRequest *imageRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:60];
UIImage *image = [UIImage imageWithData:[[AFImageDownloader defaultURLCache] cachedResponseForRequest:imageRequest].data];
关于ios - 磁盘图像缓存上的 AFNetworking 3.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36270552/