等到斯威夫特异步网络请求循环执行完毕 [英] Wait until swift for loop with asynchronous network requests finishes executing

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

问题描述

我会循环喜欢为一次的方法执行完毕了一堆网络请求的数据发送给关火力点,然后传递到一个新的视图控制器。这里是我的code:

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 

我有一对夫妇的担忧。首先,我怎么等到循环结束后,所有的网络请求是否齐全?我不能修改observeSingleEventOfType功能,它是火力SDK的一部分。另外,我会通过尝试从不同的迭代访问datesArray循环(希望是有道理的)建立某种形式的竞争状态?我一直在阅读有关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.

请注意:位置阵列是包含我需要火力访问键的数组。此外,它是重要的网络请求被异步发射了。我只是想等到一切之前我通过datesArray到下一个视图控制器的异步请求完成。

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.

推荐答案

您可以使用<一个href=\"http://commandshift.co.uk/blog/2014/03/19/using-dispatch-groups-to-wait-for-multiple-web-services/\">dispatch组当你所有的要求完成消防异步回调。

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.

var myGroup = dispatch_group_create()

override func viewDidLoad() {
    super.viewDidLoad()

    for i in 0 ..< 5 {
        dispatch_group_enter(myGroup)
        Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]).responseJSON { response in
            print("Finished request \(i)")
            dispatch_group_leave(self.myGroup)
        }
    }

    dispatch_group_notify(myGroup, dispatch_get_main_queue(), {
        print("Finished all requests.")
    })
}

输出

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

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

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