swift从完成块获取最终数组

时间:2016-07-05 00:48:07

标签: swift firebase firebase-realtime-database

我有一个从Firebase返回Assync数组的完成块,我遇到的问题是单个数组在检索它们时打印每个数组我只想在完成后检索最终数组。我怎样才能做到这一点?

这是打印的结果

[["lat": 37.33150355, "long": -122.03071596]]
[["lat": 37.33150355, "long": -122.03071596], ["lat": 37.32550194, "long": -122.01974475]]
[["lat": 37.33150355, "long": -122.03071596], ["lat": 37.32550194, "long": -122.01974475], ["lat": 37.332431, "long": -122.030713]] 
func dashMapView() {
    locationManager.delegate = self
    mapView.delegate = self
    locationManager.requestAlwaysAuthorization()
    mapView.addObserver(self, forKeyPath: "myLocation", options: NSKeyValueObservingOptions.New, context: nil)
    var helprInfo = [[String: AnyObject]]()
    currentIhelprInfo { (result) in
        //helprInfo = result
        helprInfo.append(result)
        print(helprInfo)
    }
}
// get curren Ihelper info
func currentIhelprInfo(completion: (result: [String: AnyObject]) -> ()) {
    var userAllInfo: [[String: AnyObject]]!
    let dbref = FIRDatabase.database().reference()
    dbref.child("users").queryOrderedByChild("receivePostRequest/status").queryEqualToValue(true).observeEventType(.Value, withBlock: { snapshot in
        for child in snapshot.children {
            let request = child.childSnapshotForPath("receivePostRequest")
            var lat = request.value!["lat"] as! Double
            var long = request.value!["long"] as! Double
            var userInfo = [
                "lat": lat,
                "long": long
            ]
            //var userArray = userAllInfo.append(userInfo)
            completion(result: userInfo)
        }
    })
}

1 个答案:

答案 0 :(得分:3)

您正在for循环中调用完成处理程序。确保迭代数据,首先执行逻辑并仅在准备好userInfo数组时完成它。

.observeEventType(.Value,的回调如下所示:

var helprInfo = [[String: AnyObject]]()
for child in snapshot.children {
    let request = child.childSnapshotForPath("receivePostRequest")
    var lat = request.value!["lat"] as! Double
    var long = request.value!["long"] as! Double
    var userInfo = [
        "lat": lat,
        "long": long
    ]
    helprInfo.append(userInfo)
}
completion(result: helprInfo)

你的完成处理程序只会打印在完成处理程序中传递的数组。

currentIhelprInfo { (result) in
    print(result)
}