异步图像下载 [英] Async image downloader

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

问题描述

我有写一点类通过使用NSURLConnection的进行图像的下载。
这个想法是到下载委托给这个类来避免阻塞执行。

I have write a little class to perform the download of the images by using an NSURLConnection. The idea it's to delegate the download to this class to avoid to block the execution.

所以我传递目标的UIImageView(由参)和URL的功能和开始下载:

So I pass the target UIImageView (by ref) and the url to the function and start the download:

-(void)getImage:(UIImageView**)image formUrl:(NSString*)urlStr
{
    NSLog(@"Downloader.getImage.url.debug: %@",urlStr);
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *req = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:5.0];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    NSURLConnection *c = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    [conn addObject:c];
    int i = [conn indexOfObject:c];
    [imgs insertObject:*image atIndex:i];
    [c release];
}

当它完成设置图像和更新ImageView的:

When it's finished set the image and update the imageView:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    int i = [conn indexOfObject:connection];

    NSData *rawData = [buffer objectAtIndex:i];
    UIImage *img = [UIImage imageWithData:rawData];
    UIImageView *imgView = [imgs objectAtIndex:i];
    imgView.image = img;

    [imgView setNeedsDisplay];

    [conn removeObjectAtIndex:i];
    [imgs removeObjectAtIndex:i];
    [buffer removeObjectAtIndex:i];

    if ([conn count]==0) {
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
    }
}

该系统的工作原理相当不错,但我不能得到更新的UIImageView一个UITableViewCell的细胞内部,任何想法? (实际上是细胞,当我点击它,它的更新)
还有就是要实现这个功能更好的方法? (实际上需要有:无阻塞,缓存系统)

This system works quite good, but i can't get updated the UIImageView inside the cells of a UITableViewCell, any idea ? (actually the cell it's updated when I click on it) There is a better way to implement this functionality ? (actually the need are: non-blocking, caching system)

推荐答案

塞萨尔

有关异步图像加载,缓存和线程操作,我使用SDImageCache类从 http://github.com/rs/SDWebImage。我也写了我自己的几次,但是这一次是辉煌的,我已经抛出所有我的老code了。

For async image loading, caching and threaded operation, I use SDImageCache class from http://github.com/rs/SDWebImage. I also wrote my own several times, but this one is brilliant and I've thrown all my old code away.

从它的文档:

只是#进口的UIImageView + WebCache.h 头,并调用 setImageWithURL :placeholderImage:的tableView方法:的cellForRowAtIndexPath: UITableViewDataSource方法。一切都会为你处理,从异步下载到缓存管理。

Just #import the UIImageView+WebCache.h header, and call the setImageWithURL:placeholderImage: method from the tableView:cellForRowAtIndexPath: UITableViewDataSource method. Everything will be handled for you, from async downloads to caching management.

希尔顿

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

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