2012-11-10 57 views
0

我正在使用此塊在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的東西?

回答

0

行:

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

會一直保存爲零,因爲它是內部的,如果當值「cachedResponse」是零。我想知道你是如何緩存任何東西的。

無論如何,你應該寫入分配一個NSCachedURLResponse的新實例,然後將其插入緩存中。 請注意,嘗試更改緩存的容量,這可能是問題所在。你可以用setMemoryCapacity來改變它:

+0

你是對的,這是錯誤的錯誤,我忘了粘貼一行代碼,我在創建新的cachedResponse。我正在修改我的代碼。 – Leonardo

+0

您是否嘗試通過setMemoryCapacity擴大共享URL緩存的大小? – DarthMike