【问题标题】:What is the best way to load a remote image?加载远程图像的最佳方式是什么?
【发布时间】:2012-10-26 06:55:29
【问题描述】:

我一直在研究,但没有找到这个问题的任何答案 - 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];
            }
        });
    });
}

【问题讨论】:

    标签: ios objective-c uiimage grand-central-dispatch


    【解决方案1】:

    所以我想出了一个我自己的问题的答案:
    目前主要有 3 种异步加载图像的方法。

    1. NSURLConnection
    2. GCD
    3. NSOperationQueue

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

    当使用NSURLConnection + GCD 时,我们没有取消选项,因此应该在不需要取消的时候使用(例如,加载恒定的背景图像)。

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

    【讨论】:

      【解决方案2】:

      sendAsynchronousRequest 更好,更优雅,随便你怎么称呼。但是,就个人而言,我更喜欢创建单独的 NSURLConnection 并听取其 delegatedataDelegate 方法。这样,我可以: 1. 设置我的请求超时。 2. 使用NSURLRequest 的缓存机制设置要缓存的图像(虽然它不可靠)。 2. 观看下载进度。 3. 在实际下载开始之前接收NSURLResponse(对于http代码> 400)。等等......而且,它还取决于图像大小和应用程序的一些其他要求等情况。祝你好运!

      【讨论】:

      • 下载进度是我使用代表的最大优势 - 但是似乎响应总是在图像的估计大小上显示 0。是服务器端的问题吗?除此之外,我认为委托是最混乱的方法。
      猜你喜欢
      • 1970-01-01
      • 2013-07-01
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 2010-09-10
      • 2011-09-03
      • 1970-01-01
      • 2010-11-01
      相关资源
      最近更新 更多