我正在使用此塊在iOS 5應用程序中同步下載圖像。邏輯很簡單,如果圖像在緩存中使用它,如果沒有下載它,我想NSURLRequestReturnCacheDataElseLoad正是這種行爲。NSURLRequest顯然緩存在Cache.db中,但再次請求
[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];
}
}
}
}];
我做了三個圖像的測試。當我第一次下載它們時,我可以看到'下載的MyimgName1.jpg''下載了'MyimgName2.jpg'''下載了MyimgName3.jpg'的消息,並且通過打開Cache.db,我可以看到我所有正確存儲在其中的圖像。
然而,當我試圖重新下載,只有第一個下載的圖像顯示消息「在高速緩存中找到MyimgName1.jpg」,這意味着cachedResponse是所有其他的2和3的要求零:
NSCachedURLResponse* cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
if (cachedResponse!=nil) { // <-- nil
}
我錯過了設置或創建NSCache的東西?
你是對的,這是錯誤的錯誤,我忘了粘貼一行代碼,我在創建新的cachedResponse。我正在修改我的代碼。 – Leonardo
您是否嘗試通過setMemoryCapacity擴大共享URL緩存的大小? – DarthMike