2016-08-10 38 views
1

我試圖使用NSURLSession在for循環中加載多個請求。在循環中運行NSURLSession任務

for id in ids{ 
    // ids is an Array of String 
    let url = NSURL(string:"http://example.com/something?ID=\(id)") 
    //             ^
    NSURLSession.sharedSession().dataTaskWithURL(url!){(data, response, error)in 
     if error2 != nil { 
      print(error2) 
      return 
     } 
     do{ 
      let strjson = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) 

      // Here is the problem the for loop doesn't let enough time to the NSURLSession 
     }catch let errorjson { 
      print(errorjson) 
     } 
    }.resume 
} 
+2

你是什麼意思它不會讓足夠的時間?您知道網絡活動將異步發生,因此您需要在完成處理程序中處理數據,而不是在循環後立即執行 – Paulw11

+0

您的代碼顯示格式良好。您有完成處理程序中處理每個請求的傳入數據的代碼,就像您應該這樣做。在代碼中的「這是問題」註釋中,'strjson'字符串應該包含您的JSON數據,或者如果調用'JSONObjectWithData'失敗,catch子句可能會觸發。請注意,不同的請求不會以可預測的順序完成,並且您沒有任何邏輯來確定所有請求何時完成。 –

+1

@ Paulw11問題是,我得到的數據不是每次運行代碼時我都得到一個新的訂單:/ – Yassir

回答

3

下面是使用大中央調度一種方法:

let urls = ids.map { NSURL(string:"http://example.com/something?ID=\($0)")! } 

let group = dispatch_group_create() 

// Loop through the urls array, in parallel 
dispatch_apply(urls.count, dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)) { i in 

    // Tell GCD that you are starting a new task 
    dispatch_group_enter(group) 

    NSURLSession.sharedSession().dataTaskWithURL(urls[i]) { data, response, error in 
     // Do your thing.... 

     // Tell GCD you are done with a task 
     dispatch_group_leave(group) 
    }.resume() 
} 

// Wait for all tasks to complete. Avoid calling this from the main thread!!! 
dispatch_group_wait(group, DISPATCH_TIME_FOREVER) 

// Now all your tasks have finished 
+0

是的,這是使請求順序運行的另一種方式。這意味着一次只能有一個請求正在進行 –