我正在使用此块在 iOS 5 应用程序中同步图像下载。逻辑很简单,如果图像在缓存中使用它,如果不下载它,我想 NSURLRequestReturnCacheDataElseLoad 正是这种行为。
[factory.downloadImagesQueue addOperationWithBlock:^(){
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",IP2BaseImgURL,imgName]];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:15.0];
NSCachedURLResponse* cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
if (cachedResponse!=nil) {
NSLog(@"%@ found in cache",imgName);
[delegate imageDidFinishDownload:[UIImage imageWithData:[cachedResponse data]] atIndexPath:indexPath];
} else {
NSError *error;
NSURLResponse *response;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (data == nil) {
FULL_ERROR_LOG(error)
} else {
NSLog(@"%@ downloaded",imgName);
if (![response.MIMEType isEqualToString:@"image/png"] && ![response.MIMEType isEqualToString:@"image/jpeg"]) {
NSLog(@"Found wrong mime type: %@",response.MIMEType);
[delegate imageDidEncounterErrorWhileDownload:imgName atIndexPath:indexPath];
} else {
NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:data];
[[NSURLCache sharedURLCache] storeCachedResponse:cachedResponse forRequest:(NSURLRequest *)request];
[delegate imageDidFinishDownload:[UIImage imageWithData:data] atIndexPath:indexPath];
}
}
}
}];
我用三张图片做了一个测试。当我第一次下载它们时,我可以看到消息'downloaded MyimgName1.jpg''downloaded MyimgName2.jpg''downloaded MyimgName3.jpg',通过打开Cache.db,我可以看到我所有的图像都正确存储在其中.
但是,当我尝试再次下载时,只有第一个下载的图像显示消息“MyimgName1.jpg 在缓存中找到”,这意味着对于所有其他 2 和 3 请求,cachedResponse 为 nil:
NSCachedURLResponse* cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
if (cachedResponse!=nil) { // <-- nil
}
我在 NSCache 的设置或创建中遗漏了什么吗?