use*_*232 0 nsurl key-value-observing swift alamofire
我正在使用在 iOS 10.0 下运行的 swift 3.0,我想制作一些在满足批处理条件时触发的代码。
for i in 0 ..< rex {
async code, disappears and does it stuff
}
Run Code Online (Sandbox Code Playgroud)
想象一下异步代码是一个 URL 请求的集合,只要我循环它们,基本上就是背景。现在如何在“rex”请求完成后触发更多代码?
我想设置一个计时器来每秒观察和检查,但这肯定不是一个好的解决方案。
我想启动另一个线程来简单地观察正在收集的数据,并在其配额已满时触发,但这确实比计时器更糟糕。
我想在每个 URL 请求的末尾包含一个测试,看看它是否是最后一个完成的而不是使用 NotificationCenter,但这是最佳解决方案吗?
虽然OperationQueue(aka NSOperationQueue) 在许多情况下是一个不错的选择,但它不适合您的用例。问题是 URL 请求是异步调用的。您NSOperation将在收到网络服务的响应之前完成。
使用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
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1529 次 |
| 最近记录: |