我已经编写了一个小类来使用NSURLConnection执行图像下载。它的想法是将下载委托给这个类,以避免阻塞执行。
因此,我将目标UIImageView (通过ref)和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,你有什么想法吗?(实际上,当我点击它时它会更新的单元格)有更好的方法来实现这个功能吗?(实际上需要的是:非阻塞、缓存系统)
发布于 2010-10-28 10:05:41
塞萨尔
对于异步图像加载、缓存和线程化操作,我使用http://github.com/rs/SDWebImage中的SDImageCache类。我也写了几次自己的代码,但这一次很棒,我把所有的旧代码都扔掉了。
从它的文档中:
只需
#importUIImageView+WebCache.h头,并从tableView:cellForRowAtIndexPath:UITableViewDataSource方法调用setImageWithURL:placeholderImage:方法。一切都将为您处理,从异步下载到缓存管理。
希尔顿
发布于 2012-10-18 20:20:20
只需执行以下步骤:
1) Download SDWebImage below And drag to your xcode project. Click here to Download the SDWebImage
2) Write the following code in your .h file #import "UIImageView+WebCache.h"
3) Write the following code for your image view
[yourImageView setImageWithURL:[NSURL URLWithString:@"www.sample.com/image.png"]];这就是它的..。你已经做到了!
发布于 2011-11-28 21:14:43
NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init];
[img_data setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.str_url]]]];
[pool release];https://stackoverflow.com/questions/4038726
复制相似问题