等待带有异步网络请求的 swift for 循环完成执行 [英] Wait until swift for loop with asynchronous network requests finishes executing

查看:40
本文介绍了等待带有异步网络请求的 swift for 循环完成执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个 for in 循环向 firebase 发送一堆网络请求,然后在方法完成执行后将数据传递给新的视图控制器.这是我的代码:

I would like a for in loop to send off a bunch of network requests to firebase, then pass the data to a new view controller once the the method finishes executing. Here is my code:

var datesArray = [String: AnyObject]()

for key in locationsArray {       
    let ref = Firebase(url: "http://myfirebase.com/" + "(key.0)")
    ref.observeSingleEventOfType(.Value, withBlock: { snapshot in

        datesArray["(key.0)"] = snapshot.value
    })
}
// Segue to new view controller here and pass datesArray once it is complete 

我有几个问题.首先,如何等到 for 循环完成并且所有网络请求都完成?我无法修改observeSingleEventOfType 函数,它是firebase SDK 的一部分.另外,我是否会通过尝试从 for 循环的不同迭代访问 dateArray 来创建某种竞争条件(希望有意义)?我一直在阅读有关 GCD 和 NSOperation 的文章,但我有点迷茫,因为这是我构建的第一个应用程序.

I have a couple concerns. First, how do I wait until the for loop is finished and all the network requests are complete? I can't modify the observeSingleEventOfType function, it is part of the firebase SDK. Also, will I create some sort of race condition by trying to access the datesArray from different iterations of the for loop (hope that makes sense)? I've been reading about GCD and NSOperation but I'm a bit lost as this is the first app I've built.

注意:Locations 数组是一个包含我需要在 firebase 中访问的键的数组.此外,异步触发网络请求也很重要.我只想等到所有异步请求完成后,再将日期数组传递给下一个视图控制器.

Note: Locations array is an array containing the keys I need to access in firebase. Also, it's important that the network requests are fired off asynchronously. I just want to wait until ALL the asynchronous requests complete before I pass the datesArray to the next view controller.

推荐答案

您可以使用 调度组 在所有请求完成后触发异步回调.

You can use dispatch groups to fire an asynchronous callback when all your requests finish.

这是一个使用调度组在多个网络请求都完成时异步执行回调的示例.

Here's an example using dispatch groups to execute a callback asynchronously when multiple networking requests have all finished.

override func viewDidLoad() {
    super.viewDidLoad()

    let myGroup = DispatchGroup()

    for i in 0 ..< 5 {
        myGroup.enter()

        Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON { response in
            print("Finished request (i)")
            myGroup.leave()
        }
    }

    myGroup.notify(queue: .main) {
        print("Finished all requests.")
    }
}

输出

Finished request 1
Finished request 0
Finished request 2
Finished request 3
Finished request 4
Finished all requests.

这篇关于等待带有异步网络请求的 swift for 循环完成执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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