我使用的是在iOS 10.0下运行的swift 3.0,我想制作一些在满足批处理条件时触发的代码。
for i in 0 ..< rex {
async code, disappears and does it stuff
}假设异步代码是URL请求的集合,只要我遍历它们,基本上就是后台。现在,当"rex“请求完成时,我该如何触发更多的代码呢?
我想设置一个计时器来监视和检查每一秒,但这肯定不是一个好的解决方案。
我想启动另一个线程来简单地观察正在收集的数据,并在它的配额已满时触发,但实际上这比计时器更糟糕。
我正在考虑在每个URL请求的末尾包含一个测试,看看它是否是最后一个完成的,然后使用NotificationCenter,但这是最优的解决方案吗?
发布于 2016-09-22 09:36:56
虽然OperationQueue (又称NSOperationQueue)在许多情况下是一个很好的选择,但它不适合您的用例。问题是URL请求是异步调用的。您的NSOperation将在您从get服务获得响应之前完成。
请改用DispatchGroup
let group = DispatchGroup()
// We need to dispatch to a background queue because we have
// to wait for the response from the webservice
DispatchQueue.global(qos: .utility).async {
for i in 0 ..< rex {
group.enter() // signal that you are starting a new task
URLSession.shared.dataTask(with: urls[i]) { data, response, error in
// handle your response
// ....
group.leave() // signal that you are done with the task
}.resume()
}
group.wait() // don't ever call wait() on the main queue
// Now all requests are complete
}发布于 2016-09-22 03:54:37
所以我很确定你想要的是found here。基本上,您希望使用GCD并拥有一个完成闭包。这是一行代码,总是让我咯咯地笑。关于is here主题的更长的帖子。
发布于 2016-09-22 04:01:50
你要找的是NSOperationQueue (或者Swift 3中的OperationQueue )。这是一个Swift tutorial (可能有点过时了)。这是苹果的documentation on it --在Swift 3中,他们去掉了所有NS前缀,所以它是OperationQueue / Operation。
基本上,您应该将每个URL任务作为Operation添加到OperationQueue中,并将每个URL任务作为依赖项添加到一个“完成”Operation中,然后将其添加到队列中。然后,一旦你的所有URL任务完成,它就会调用你的done操作,你可以设置它来做任何你想做的事情。
您可能需要创建Operation的子类,以便正确地更新isExecuting和isFinished属性。This question may be of some help here。
https://stackoverflow.com/questions/39623794
复制相似问题