gpt4 book ai didi

ios - NSURLSession 任务在 for 循环中运行

转载 作者:搜寻专家 更新时间:2023-11-01 06:05:24 26 4
gpt4 key购买 nike

我正在尝试使用 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
}

最佳答案

这是使用 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

关于ios - NSURLSession 任务在 for 循环中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38885316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com