2016-09-21 58 views
0

在我的應用程序中,我打開ViewController時必須下載近500張圖像。一次下載500張圖片並不是一個好主意。我想一次保持5個活動的異步下載。五分之一中的任何一個完成後,應該開始下一個。iOS下載批量圖像的最佳方式

我也有一個刷新控件,它將重新從頭開始下載所有的圖像。

我可以採用哪種技術來實現這種模式?

這裏是我試過到目前爲止,

信號燈在財產申報

private var semaphore = dispatch_semaphore_create(5) 

創建讓Web服務響應後,

private func startDownloadingImages() { 
     for place in places { 
      dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER) 
      self.downloadImageForPlace(place) 
     } 
    } 

private func downloadImageForPlace(place: Place) { 
     ApplicationControls.getImageForPlace(place, withCompletion: { (image, error) ->() in 
      // error checks 
      dispatch_async(dispatch_get_main_queue(), { 
       // UI update 
       dispatch_semaphore_signal(self.semaphore) 
      }) 
     }) 
    } 

但是當我點擊刷新控制,應用程序鎖在dispatch_semaphore_wait,我可以找到一種方法來重置信號量。

回答

1

我會用一個OperationQueue這樣

let queue = OperationQueue() 
queue.maxConcurrentOperationCount = 5; 

for url in imageUrls { 
    queue.addOperationWithBlock {() -> Void in 

     let img1 = Downloader.downloadImageWithURL(url) 

     NSOperationQueue.mainQueue().addOperationWithBlock({ 
      //display the image or whatever 
     }) 
    } 


} 

你可以用這個

queue.cancelAllOperations(); 

停止你的操作,然後只需重新啓動整個事情。

你唯一需要改變的是你的請求必須是同步的。因爲這種方法不適用於回調。

+0

我甚至嘗試過。我不知道爲什麼。 NSOperationQueue不服從屬性maxConcurrentOperationCount。所有500個下載都在for循環中。 – iOS

+1

當然它們在for循環中,但是操作隊列一次不會執行超過5個操作。 – ben