2014-10-12 107 views
4

我需要運行一些代碼請求多個HTTP資源收集一些數據。如何知道在iOS中何時執行並行HTTP請求?

我讀過大量的文檔資料,我已經找到了我應該使用GCD和調度組

  1. dispatch_group_create()
  2. 創建一個組對於每個要求:
    • dispatch_group_enter()輸入派遣組
    • 運行請求
    • 當接收到一個響應,離開組dispatch_group_leave()
  3. 等待與dispatch_group_wait()
  4. 鬆開組dispatch_release()

但我不知道,如果這種做法可能有一些缺陷 - 或有沒有更好的方式來等待相似請求的完成?

下面的代碼看起來運行良好:

// Just send a request and call the when finished closure 
    func sendRequest(url: String, whenFinished:() -> Void) { 
     let request = NSMutableURLRequest(URL: NSURL(string: url)) 
     let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { 
      (data, response, error) -> Void in 
      whenFinished() 
     }) 
     task.resume() 
    } 

    let urls = ["http://example.com?a", 
     "http://example.com?b", 
     "http://example.com?c", 
     "http://example.com?d", 
     "http://invalid.example.com"] 

    var fulfilledUrls: Array<String> = [] 

    let group = dispatch_group_create(); 

    for url in urls { 
     dispatch_group_enter(group) 

     sendRequest(url, { 
      () in 
      fulfilledUrls.append(url) 
      dispatch_group_leave(group) 
     }) 

    } 

    dispatch_group_wait(group, DISPATCH_TIME_FOREVER); 

    for url in fulfilledUrls { println(url) } 

回答

3

是啊,這是基本的想法,雖然你最好使用dispatch_group_notify代替dispatch_group_wait因爲dispatch_group_wait阻塞調用線程,直到該組完成,而dispatch_group_notify將調用當該組完成時,一個塊在沒有的過渡期間阻塞調用線程。