2012-10-26 102 views
3

我一直在研究,並沒有找到任何答案這個問題 - 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]; 
     } 
    }]; 
} 

OR

- (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]; 
      } 
     }); 
    }); 
} 

回答

1

所以我想出了一個我自己的問題的答案:
目前有3種主要方式加載圖像異步。

  1. NSURLConnection的
  2. GCD
  3. NSOperationQueue

選擇最好的方法是爲每一個問題的不同。
例如,在UITableViewController中,我將使用第三個選項(NSOperationQueue)爲每個單元格加載圖像,並確保在分配圖片之前單元格仍然可見。如果單元格不再可見,則應取消操作,如果VC彈出堆棧,則應取消整個隊列。

當使用NSURLConnection + GCD時,我們無法取消選擇,因此應在無需使用此選項時使用(例如,加載恆定背景圖像)。

另一個好建議是將該映像存儲在緩存中,即使不再顯示,並在啓動另一個加載過程之前在緩存中查找它。

0

sendAsynchronousRequest較好,優雅,無論你怎麼稱呼它。但是,我個人更喜歡創建單獨的NSURLConnection,並傾聽其delegatedataDelegate方法。這樣,我可以:1.設置我的請求超時。 2.使用NSURLRequest的緩存機制設置要緩存的圖像(儘管如此,它不可靠)。 2.觀看下載進度。 3.在實際下載開始之前接收NSURLResponse(對於http代碼> 400)。等等......並且,它還取決於像應用程序的圖像大小和其他一些要求。祝你好運!

+0

下載進度對我來說是使用代表的最大優勢 - 但它似乎響應始終在圖像的估計大小上顯示0。服務器端有問題嗎? 除此之外,我認爲代表是最麻煩的方法。 – Yariv

相關問題