我正在尝试使用NSURLSession
在for循环中加载多个请求。
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
}
答案 0 :(得分:5)
这是使用Grand Central Dispatch的一种方法:
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