Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/93.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 加载远程映像的最佳方式是什么?_Ios_Objective C_Uiimage_Grand Central Dispatch - Fatal编程技术网

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

Ios 加载远程映像的最佳方式是什么?,ios,objective-c,uiimage,grand-central-dispatch,Ios,Objective C,Uiimage,Grand Central Dispatch,我一直在研究,还没有找到这个问题的答案-sendAsynchronousRequest和dataWithContentsOfURL 哪个更有效?更优雅?更安全的?等等 - (void)loadImageForURLString:(NSString *)imageUrl { self.image = nil; [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; NSURLRequ

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


sendAsynchronousRequest
更好、更优雅,无论您如何称呼它。但是,就我个人而言,我更喜欢创建单独的
NSURLConnection
,并聆听它的
delegate
dataDelegate
方法。这样,我可以:1。设置我的请求超时。2.使用
NSURLRequest
的缓存机制设置要缓存的图像(尽管不可靠)。2.观看下载进度。3.在实际下载开始之前接收
nsurresponse
(对于http代码>400)。等此外,它还取决于案例,如图像大小,以及应用程序的一些其他要求。祝你好运

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

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

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


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

    下载进度是我使用代理的最大优势-但是似乎响应总是显示图像估计大小为0。服务器端有问题吗?除此之外,我认为委托是最混乱的方法。
    - (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];
                }
            });
        });
    }