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
}
你是什麼意思它不會讓足夠的時間?您知道網絡活動將異步發生,因此您需要在完成處理程序中處理數據,而不是在循環後立即執行 – Paulw11
您的代碼顯示格式良好。您有完成處理程序中處理每個請求的傳入數據的代碼,就像您應該這樣做。在代碼中的「這是問題」註釋中,'strjson'字符串應該包含您的JSON數據,或者如果調用'JSONObjectWithData'失敗,catch子句可能會觸發。請注意,不同的請求不會以可預測的順序完成,並且您沒有任何邏輯來確定所有請求何時完成。 –
@ Paulw11問題是,我得到的數據不是每次運行代碼時我都得到一個新的訂單:/ – Yassir