2016-06-21 51 views
0

我已經使用sdwebimage來緩存圖像。 現在imagesArr是我想要爲所有單元格首先顯示的圖像數組。 我在後臺下載圖像,然後保存到磁盤,所以當我想離線模式下,我可以從磁盤中獲得這些圖像。圖像在收集視圖單元中不正確

但在某些情況下,當我滾動collectionView圖像設置不正確,然後再滾動圖像看起來是正確的。

這是我在cellForItemAtIndexPath中實現的以下代碼。我試圖調試,但似乎數據是正確的,圖像名稱也是正確的。

此外,collectionView在滾動中滯後。請幫我找到問題。

if(imagesArr.count>0) 
{ 
    ClothesImage *obj_image=[imagesArr objectAtIndex:0]; 
    NSString *fileName = [stringPath stringByAppendingFormat:@"/%@",obj_image.imagePath]; 
    NSLog(@"FILES NAMES %@ ", obj_image.imagePath); 
    NSData *data = [NSData dataWithContentsOfFile:fileName]; 
    if(data!=nil){ 
     UIImage *image=[UIImage imageWithData:data]; 
     cell.imgProduct.image=image; 
    } 
    else{ 
     NSString *offline=[user_defaults objectForKey:@"offline"]; 

     if([offline integerValue]==0){ 
      cell.imgProduct.image=[UIImage imageNamed:@"noImageThumb"]; 
      NSString *str_url=[NSString stringWithFormat:@"%@/%@",WEB_THUMB_IMAGE,obj_image.imagePath]; 
      str_url = [NSString stringWithFormat: @"%@",[str_url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 

      [cell.imgProduct setImageWithURL:[NSURL URLWithString:str_url] placeholderImage:[UIImage imageNamed:@"noImageThumb"] options: SDWebImageRefreshCached]; 

      SDWebImageManager *manager = [SDWebImageManager sharedManager]; 
      [manager downloadWithURL:[NSURL URLWithString:str_url] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) { 
       NSString *stringPathImage = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"WebThumb"]; 
       NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)]; 
       NSString *fileName = [stringPathImage stringByAppendingFormat:@"/%@",obj_image.imagePath]; 
       [data writeToFile:fileName atomically:YES]; 
       NSLog(@"DOWNLOADED IMAGE %@",fileName); 

    }]; 
     } 
     else 
     { 
      cell.imgProduct.image=[UIImage imageNamed:@"noImageThumb"]; 
     } 
    } 
} else{ 
    cell.imgProduct.image=[UIImage imageNamed:@"noImageThumb"]; 
} 
+0

不正確=錯誤的位置或只是noImageThumb而不是實際的圖像? – Shubhank

+0

不正確的意思是一些錯誤的位置隨機圖像。 –

回答

1

我認爲有幾種方法可以改善這一點。

看起來您似乎在重複SDWebImage爲您所做的大量工作。該庫將緩存圖像並按需提取它們。您應該考慮讓該庫預取文件到緩存中,而不是嘗試預取並將它們寫入磁盤。最後到-cellForRowAtIndexPath時,您只需要兩種情況:一種用於在設備脫機時設置圖像,另一種用於從SDWebImage提供的緩存中提取或設置圖像:

[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] 
        placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; 

就是這樣。你所做的所有緩存和切換都不是必需的。另一件可以肯定的事情是在你的單元格子類方法-prepareForReuse中,你正在扼殺圖像。

+0

所以當沒有互聯網時,它會自動從緩存中獲取圖片,來自url的absoluteString圖片。 –

+0

是的,假設圖像在緩存中。 – isaac