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]; 
});