我编写了一个小类来使用 NSURLConnection 执行图像的下载。
其想法是将下载委托给此类以避免阻止执行。
因此,我将目标 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,有什么想法吗? (实际上,当我点击它时,单元格会更新)
有更好的方法来实现这个功能吗? (实际上需要的是:非阻塞、缓存系统)
Cesar
对于异步图像加载、缓存和线程操作,我使用来自http://github.com/rs/SDWebImage http://github.com/rs/SDWebImage。我也自己写了好几次,但是这个非常棒,而且我已经扔掉了所有旧代码。
从它的文档来看:
Just #import
the UIImageView+WebCache.h
标头,并调用setImageWithURL:placeholderImage:
方法从tableView:cellForRowAtIndexPath:
UITableViewDataSource 方法。从异步下载到缓存管理,一切都将为您处理。
Hilton
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)