7

如何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];


});

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

4

3 回答 3

9

试图回答您的主要问题“我怎样才能UICollectionview异步加载图像?”

我会在这里建议“ Natasha Murashev ”提供的解决方案,这对我来说效果很好,而且很简单。

如果imgURL = [allImage objectAtIndex:k];allImage属性中保留 URL 数组,则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:,该方法将异步加载图像并在成功下载图像时自动更新 CollectionView 中的单元格。

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

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

Swift 中的 Swift 2.2 解决方案。

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
    }
于 2013-12-13T03:53:09.250 回答
0

此代码创建串行队列:

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

因此,队列中的每个任务都在同一线程中连续执行。因此,每个加载任务都会通过睡眠来维持您的单个工作线程,这会减慢所有加载过程。

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

dispatch_queue_t imageLoadQueue = dispatch_queue_create("com.GMM.assamkar", DISPATCH_QUEUE_CONCURRENT);
于 2013-08-03T09:04:31.063 回答
-1

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

延迟加载.h 延迟加载
.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;
}

在此处下载演示

于 2013-08-03T12:32:42.430 回答