异步图像下载器

时间:2010-10-28 00:08:56

标签: iphone image user-interface asynchronous download

我已经编写了一个小类来使用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,任何想法? (实际上是单击它时更新的单元格) 有更好的方法来实现此功能吗? (实际上需要的是:非阻塞,缓存系统)

5 个答案:

答案 0 :(得分:6)

塞萨尔

对于异步映像加载,缓存和线程操作,我使用http://github.com/rs/SDWebImage中的SDImageCache类。我也写过几次,但是这个很棒,而且我把所有旧代码扔掉了。

从其文档:

  

只需#import UIImageView+WebCache.h标头,并从setImageWithURL:placeholderImage: UITableViewDataSource方法调用tableView:cellForRowAtIndexPath:方法。从异步下载到缓存管理,一切都将为您处理。

希尔顿

答案 1 :(得分:3)

只需按照以下步骤操作:

    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"]];

多数民众赞成......你做完了!!!

答案 2 :(得分:1)

NSAutoreleasePool *pool=[[NSAutoreleasePool alloc]init];
    [img_data setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.str_url]]]];
    [pool release];

答案 3 :(得分:1)

  

这个系统工作得很好,但我无法更新UIImageView   在UITableViewCell的细胞内,有什么想法吗? (实际上是细胞   当我点击它时它会更新)有一种更好的实现方式   这个功能? (实际上需要的是:非阻塞,缓存   系统

您是否尝试过使用 [tableView reloadData]; 在connectionDidFinishLoading方法结束时调用它

答案 4 :(得分:1)

简单地使用SDWebImage。我也在使用那个。加载图像顺利。我使用下面的代码来显示来自网址的图片

[myImageView setImageWithURL:[NSURL URLWithString:@"www.sample.com/image.png"] placeholderImage:[UIImage imageNamed:@"lod.png"] 
success:^(UIImage *image, BOOL cached)
{
    productImageDetails.image = image;
} 
failure:^(NSError *error) {
    productImageDetails.image =[UIImage imageNamed:@"no_image.jpg"];
}];

成功部分将显示来自webService的图像。而且,如果有任何图像无法加载或任何其他故障问题,您可以在那里加载自己的图像。 There是该示例的更多功能。你可以参考一下。