需要同时发出两个HTTP网络请求(一旦完成就使用完成处理程序) [英] Need to make two HTTP network requests simultaneously (with a completion handler once both finish)

查看:207
本文介绍了需要同时发出两个HTTP网络请求(一旦完成就使用完成处理程序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我需要发出两个HTTP GET请求,并且只有在两个完成后才能处理它们的结果。我在每个单独的网络请求上都有一个完成处理程序,但它没有帮助,因为我不知道何时检索来自两个请求的数据。

I have a situation where I need to make two HTTP GET requests and handle their results only after both are finished. I have a completion handler on each individual network request but it isn't helpful as I don't know when data from both requests are retrieved.

我的经验有限GCD但是现在Swift 3已经出局了,我试图找出如何运行多个任务并为它们设置一个完成处理程序。我的研究表明,GCD或NSOperationQueue可能是我正在寻找的解决方案。任何人都可以帮助建议哪个工具适合这项工作以及代码在Swift 3中的样子?

I have limited experience with GCD but now that Swift 3 is out, I am trying to figure out how to run multiple tasks and have a single completion handler for them. My research has shown that GCD or NSOperationQueue may be the solution I'm looking for. Can anyone help suggest which tool fits the job and what the code might look like in Swift 3?

推荐答案

您应该使用调度组,在发出请求之前进入组,并将组留在请求的完成处理程序中。所以,让我们假设你有一个执行异步请求的方法,但是提供了一个完成处理程序参数,它是一个在网络请求完成时将被调用的闭包:

You should use dispatch groups, entering the group before you issue the request, and leaving the group in the completion handler for the request. So, let's assume, for a second, that you had some method that performed an asynchronous request, but supplied a completion handler parameter that was a closure that will be called when the network request is done:

func perform(request: URLRequest, completionHandler: @escaping () -> Void) { ... }

要启动这两个并发请求,并在完成后收到通知,您可以执行以下操作:

To start these two concurrent requests, and be notified when they're done, you'd do something like:

let group = DispatchGroup()

group.enter()
perform(request: first) {
    group.leave()
}

group.enter()
perform(request: second) {
    group.leave()
}

group.notify(queue: .main) {
    print("both done")
}

显然,你的执行(请求:) 的实现可能会有很大差异(例如,你可能会让闭包传回数据),但是无论你是在写你的模式都是一样的使用 URLSession 或使用Alamofire拥有网络代码。只需使用GCD组,在创建请求时进入组,并将组保留在异步请求的完成处理程序中。

Clearly, your implementation of perform(request:) may vary significantly (e.g. you might have the closure pass the data back), but the pattern is the same whether you are writing your own networking code with URLSession or using Alamofire. Just use GCD groups, entering the group when you create the requests, and leaving the group in the completion handler of the asynchronous request.

这篇关于需要同时发出两个HTTP网络请求(一旦完成就使用完成处理程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆