加载远程图像的最佳方式是什么?

我一直在研究,并没有find任何答案这个问题 – sendAsynchronousRequest与dataWithContentsOfURL。

哪个更有效率? 更优雅? 更安全吗? 等等

- (void)loadImageForURLString:(NSString *)imageUrl { self.image = nil; [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * response, NSData * data, NSError * connectionError) { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; if (data) { self.image = [UIImage imageWithData:data]; } }]; } 

要么

 - (void)loadRemoteImage { self.image = nil; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ NSData * imageData = [NSData dataWithContentsOfURL:self.URL]; if (imageData) self.image = [UIImage imageWithData:imageData]; dispatch_async(dispatch_get_main_queue(), ^{ if (self.image) { [self setupImageView]; } }); }); } 

所以我提出了一个自己的问题的答案:
目前有三种主要的方式来加载图像asynchronous。

  1. NSURLConnection的
  2. GCD
  3. NSOperationQueue

select最好的方法是不同的每个问题。
例如,在UITableViewController ,我将使用第三个选项( NSOperationQueue )为每个单元NSOperationQueue载图像,并确保单元格在分配图片之前仍然可见。 如果单元格不再可见,则应取消该操作,如果VCpopup堆栈,则应取消整个队列。

当使用NSURLConnection + GCD时,我们没有select取消的选项,所以在没有必要的时候使用(例如,加载一个常量的背景图片)。

另一个好的build议是将该图像存储在caching中,甚至不再显示,并在启动另一个加载过程之前在caching中查找它。

sendAsynchronousRequest更好,更优雅,无论你怎么称呼它。 但是,我个人更喜欢创build单独的NSURLConnection并监听它的delegatedataDelegate方法。 这样,我可以:1.设置我的请求超时。 2.使用NSURLRequest的caching机制设置caching(尽pipe如此,这是不可靠的)。 2.观看下载进度。 3.实际下载之前接收NSURLResponse (对于http代码> 400)。 等等…而且,它也取决于像应用程序的图像大小和其他一些要求。 祝你好运!

Interesting Posts