我编写了一个小类来使用 NSURLConnection 执行图像下载。 其想法是将下载委托(delegate)给此类以避免阻止执行。
因此,我将目标 UIImageView (通过引用)和 url 传递给函数并开始下载:
-(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:
- (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];
}
}
这个系统工作得很好,但我无法更新 UITableViewCell 单元格内的 UIImageView,知道吗? (实际上,当我点击它时,单元格会更新) 有更好的方法来实现这个功能吗? (实际上需要的是:非阻塞、缓存系统)
最佳答案
塞萨尔
对于异步图像加载、缓存和线程操作,我使用 http://github.com/rs/SDWebImage 中的 SDImageCache 类。我也自己写过好几次,但是这个非常棒,而且我已经扔掉了所有旧代码。
来自其文档:
Just
#import
theUIImageView+WebCache.h
header, and call thesetImageWithURL:placeholderImage:
method from thetableView:cellForRowAtIndexPath:
UITableViewDataSource method. Everything will be handled for you, from async downloads to caching management.
希尔顿
关于iphone - 异步图像下载器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4038726/