NSURLRequest显然缓存在Cache.db中,但再次请求

时间:2012-11-10 09:56:42

标签: objective-c nsurlconnection nsurlcache

我正在使用此块在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];
                }
            }
        }

    }];

我用三张图片做了测试。当我第一次下载它们时,我可以看到消息'下载MyimgName1.jpg''已下载MyimgName2.jpg''已下载MyimgName3.jpg',并打开Cache.db我可以看到我的所有图像都正确存储在其中

然而,当我再次尝试下载时,只有第一个下载的图像显示消息“在缓存中找到MyimgName1.jpg”,这意味着所有其他2和3请求的cachedResponse为零:

    NSCachedURLResponse* cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
    if (cachedResponse!=nil) { // <-- nil
    }

我在设置或创建NSCache时遗漏了什么?

1 个答案:

答案 0 :(得分:0)

该行:

[[NSURLCache sharedURLCache] storeCachedResponse:cachedResponse forRequest:(NSURLRequest *)request];

当'cachedResponse'的值为零时,将始终存储为nil。我想知道你是如何缓存的。

无论如何,在将其插入缓存之前,您应该编写一个新的NSCachedURLResponse实例。 作为旁注,尝试更改缓存容量,这可能是问题所在。您可以使用setMemoryCapacity更改它: