将图像异步加载到UICollectionView?

时间:2013-08-03 08:38:33

标签: ios objective-c asynchronous uicollectionview

如何异步将图像加载到UICollectionview? 在以下方法中?

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

 bookImage = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", docPath, [[preview objectAtIndex:indexPath.row] lastPathComponent]]];
 [[cell grid_image] setImage:bookImage];

}

viewdidload()中,我使用以下异步调用将图片加载到“预览”NSMutablearray

 dispatch_queue_t imageLoadQueue = dispatch_queue_create("com.GMM.assamkar", NULL);

dispatch_async(imageLoadQueue, ^{
    //Wait for 5 seconds...
    usleep(1000000);
    docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];


    for(int k=0; k <[allImage count] ;k++){


        imgURL = [allImage objectAtIndex:k];
        [imagePreview addObject:imgURL];
        imgData=[NSData dataWithContentsOfURL:[NSURL URLWithString:imgURL]];


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

    }

    [[self collectionView] reloadData];


});

请帮助我......现在花了太多时间装货......

3 个答案:

答案 0 :(得分:8)

尝试回答您的主要问题“如何以异步方式将图像加载到UICollectionview?”

我建议使用“ Natasha Murashev here提供的解决方案,这对我很有用,而且很简单。

如果imgURL = [allImage objectAtIndex:k];属性中allImage位于collectionView:cellForItemAtIndexPath:,请保留一系列网址,然后像这样更新您的- (PSTCollectionViewCell *)collectionView:(PSTCollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { NSURL *url = [NSURL URLWithString:[allImage objectAtIndex:indexPath]]; [self downloadImageWithURL:url completionBlock:^(BOOL succeeded, NSData *data) { if (succeeded) { cell.grid_image.image = [[UIImage alloc] initWithData:data]; } }]; } 方法:

downloadImageWithURL:completionBlock:

将方法- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *data))completionBlock { NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if (!error) { completionBlock(YES, data); } else { completionBlock(NO, nil); } }]; } 添加到您的类中,该方法将异步加载图像并在成功下载图像时自动更新CollectionView中的单元格。

public typealias ImageFetchCompletionClosure = (image: UIImage?, error: NSError?, imageURL: NSURL?) -> Void

extension String {
   func fetchImage(completionHandler: (image: UIImage?, error: NSError?, imageURL: NSURL?) -> Void) {
        if let imageURL = NSURL(string: self) {
            NSURLSession.sharedSession().dataTaskWithURL(imageURL) { data, response, error in
                guard
                    let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
                    let mimeType = response?.MIMEType where mimeType.hasPrefix("image"),
                    let data = data where error == nil,
                    let image = UIImage(data: data)
                    else {
                        if error != nil {
                            completionHandler(image: nil, error: error, imageURL: imageURL)
                        }
                        return
                }
                dispatch_sync(dispatch_get_main_queue()) { () -> Void in
                    completionHandler(image: image, error: nil, imageURL: imageURL)
                }
            }.resume()
        }
    }
}

我看到你试图在视图出现之前预先加载图像,所以也许我的解决方案不是你的意思,但从你的问题来看,这很难说。不管如何,你也可以用这个来达到你想要的效果。

Swift 2.2 Swift中的解决方案。

    "url_string".fetchImage { (image, error, imageURL) in
        // handle different results, either image was downloaded or error received
    }

使用示例:

{{1}}

答案 1 :(得分:0)

此代码创建串行队列:

dispatch_queue_t imageLoadQueue = dispatch_queue_create("com.GMM.assamkar", NULL);

因此,每个任务IN QUEUE都在相同的线程中执行。因此,对于每个加载任务,您的单个工作线程都会通过睡眠来维持,从而减慢所有加载过程。

使用类似的东西来使用异步CONCURRENT队列:

dispatch_queue_t imageLoadQueue = dispatch_queue_create("com.GMM.assamkar", DISPATCH_QUEUE_CONCURRENT);

答案 2 :(得分:-1)

根据您的要求使用延迟加载文件。

LazyLoad.h
LazyLoad.m

像这样使用它们

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    [cell addSubview:[self addViewWithURL:@"http://openwalls.com/image/399/explosion_of_colors_1920x1200.jpg" NFrame:CGRectMake(0, 0, 50, 50)]];

    cell.backgroundColor=[UIColor blueColor];
    return cell;
}

-(UIView*)addViewWithURL:(NSString*)urlStr NFrame:(CGRect)rect
{
    LazyLoad *lazyLoading;

    lazyLoading = [[LazyLoad alloc] init];
    [lazyLoading setBackgroundColor:[UIColor grayColor]];
    [lazyLoading setFrame:rect];

    [lazyLoading loadImageFromURL:[NSURL URLWithString:urlStr]];
    return lazyLoading;
}

Download Demo Here