将图像异步加载到 UICollectionView? [英] Load image to UICollectionView Asynchronously?

查看:22
本文介绍了将图像异步加载到 UICollectionView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将图像异步加载到 UICollectionview?在下面的方法里面?

How can i load images to a UICollectionview asynchronously? Inside following method?

- (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

In viewdidload() i am using following asynch call to load images to "preview "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];


});

请帮帮我..现在加载时间太长了...

Please help me..Now its taking too much time for loading...

推荐答案

尝试回答您的主要问题如何将图像异步加载到 UICollectionview?"

Trying to answer your main question "How can i load images to a UICollectionview asynchronously?"

我建议Natasha Murashev"这里,这对我来说效果很好,而且很简单.

I would suggest solution offered by "Natasha Murashev" here, which worked nicely for me and it's simple.

如果这里 imgURL = [allImage objectAtIndex:k];allImage 属性中保留 URL 数组,则更新您的 collectionView:cellForItemAtIndexPath: 方法如下:

If here imgURL = [allImage objectAtIndex:k]; in allImage property you keep array of URLs, then update your collectionView:cellForItemAtIndexPath: method like this:

- (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: ,当图像下载成功时,它将异步加载图像并自动更新 CollectionView 中的单元格.

And add method downloadImageWithURL:completionBlock: to your class, which will load images asynchronously and update cells in CollectionView automatically when images are successfully downloaded.

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

我看到您尝试在视图出现之前预加载图像,所以也许我的解决方案不是您想要的,但是从您的问题很难说.无论如何,你也可以通过它实现你想要的.

I see you try to preload images before view appears so maybe my solution isn't what you what, but from your question it's hard to say. Any how, you can achieve what you want with this as well.

斯威夫特 2.2Swift 中的解决方案.

Swift 2.2 Solution in Swift.

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()
        }
    }
}

使用示例:

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

这篇关于将图像异步加载到 UICollectionView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆