在Swift 3.0中跟踪一批HTTP请求的解决方案 [英] A solution to track a batch of HTTP requests in swift 3.0
问题描述
我正在使用在iOS 10.0下运行的swift 3.0,我想制作一些在满足批处理条件时将触发的代码.
I am using swift 3.0 running under iOS 10.0 and I want to craft some code that fires when a batch condition is met.
for i in 0 ..< rex {
async code, disappears and does it stuff
}
想象一下,异步代码是URL请求的集合,当我循环遍历它们时,它们基本上是后台的.现在,当"rex"请求完成后,我该如何触发更多代码?
Imagine the async code is a collection of URL requests, that basically background as soon as I loop thru them. Now how can I fire off more code when "rex" requests have completed?
我想设置一个计时器来监视和检查每一秒,但这肯定不是一个好的解决方案.
I thought of setting up a timer to watch and check every second, but its surely not a good solution.
我以为可以启动另一个线程来简单地监视正在收集的数据,并在其配额已满时触发,但这确实比计时器更糟糕.
I thought kicking off another thread to simply watch the data being collected, and fire when its quota is full, but well that's worse then the timer really.
我正在考虑在每个URL请求的末尾包含一个测试,以查看它是否是最后一个完成并使用NotificationCenter的示例,但这是最佳解决方案吗?
I am thinking to include a test at the end of each URL request to see if it was the last that completed and than uses the NotificationCenter, but is this the optimal solution?
推荐答案
虽然OperationQueue
(又名NSOperationQueue
)在很多情况下都是不错的选择,但它并不适合您的用例.问题在于URL请求被异步调用.您的NSOperation
将在您从网络服务获得响应之前完成.
While OperationQueue
(aka NSOperationQueue
) is a good choice in many cases, it's not suitable for your use case. The problem is that URL requests are called asynchronously. Your NSOperation
will finish before you get a response from the webservice.
改为使用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
}
这篇关于在Swift 3.0中跟踪一批HTTP请求的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!