0

嗨iam使用PST Collectionview類似UIcollectionview。我想從我的文檔目錄加載圖像集合view.First嘗試同步的方式,但它太慢..所以知道我怎麼能異步加載圖像到collectionview。異步圖像加載不起作用?

viewDidLoad中

我添加以下代碼,以便將圖像下載到我的文檔目錄

dispatch_queue_t imageLoadQueue = dispatch_queue_create("com.aaa.nkp",NULL); 

    dispatch_async(imageLoadQueue, ^{ 

     usleep(1000000); 
     docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 


     for(int i=0; i <[Images count] ;i++){ 


      imgURL = [Images objectAtIndex:i]; 
      [imagePreview addObject:imgURL]; 
      imgData=[NSData dataWithContentsOfURL:[NSURL URLWithString:imgURL]]; 


      [imgData writeToFile:[NSString stringWithFormat:@"%@/%@", docPath, [imgURL lastPathComponent]] atomically:YES]; 


     } 

        [[self collectionView] reloadData]; 



    }); 

和的CollectionView cellforitem()內梅索德

- (PSTCollectionViewCell *)collectionView:(PSTCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { 


    cell = nil; 
    cell = (GMMCollectionViewCell *)[self.collectionView dequeueReusableCellWithReuseIdentifier:@"test" forIndexPath:indexPath]; 
    cell.tag = indexPath.row; 
    docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    BOOL isImageLoaded = YES; 
    bookImage = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", docPath, [[Images objectAtIndex:indexPath.row]   lastPathComponent]]]; 

    if(bookImage == nil) 
     isImageLoaded = NO; 

    if(!isImageLoaded){ 
     [[cell grid_image] setImage:[UIImage imageNamed:@"Placeholder.png"]]; 

    } 
    else{ 
     [[cell grid_image] setImage:bookImage ]; 

    } 

    return cell; 
} 
+0

你是如何嘗試異步加載圖像的? – Wain

+0

@navi直接在圖像載入「UIImageView」 –

+0

我只是試圖從該文件目錄加載圖像。我沒有添加任何代碼,但我怎麼能從那裏加載圖像異步collectionview? – Navi

回答

0

你爲什麼下載圖像到你的目錄?

要異步下載圖像,我真的建議你使用SDWebImage。這是一個很好的庫,可以通過cocoapods輕鬆安裝。

這裏的項目頁面:https://github.com/rs/SDWebImage

該庫甚至將圖像存儲在緩存中,所以我認爲您可以刪除所有此下載代碼。

下載的lib和integreted到項目後,只是刪除了所有以前的代碼,在後臺下載),並把這裏面你的CollectionView的cellForItemAtIndexPath:

// Here we use the new provided setImageWithURL: method to load the web image 
    [cell.imageView setImageWithURL:[NSURL URLWithString:@"anyURLhere"] 
        placeholderImage:[UIImage imageNamed:@"placeholder.png"]]; 

就在今年,像變魔術一樣。該lib會將placeHolder圖像放入imageView中,自動下載圖像,並自動更改佔位符圖像和下載的圖像。試一下。

如果您需要更多信息,可以檢查項目的github頁面。

+0

請告訴我,我怎麼能disaply圖像異步 – Navi

+0

我編輯anwser,看看,並告訴我,如果它幫助 –

+0

無法這一框架添加到我的Xcode,做ü有使用SDWebimage任何示例項目????? – Navi

1

您需要更新主線程上的UI。嘗試在你的[[self collectionView] reloadData];這樣的環繞代碼:

dispatch_async(dispatch_get_main_queue(), ^{ 
    [[self collectionView] reloadData]; 
});