简体   繁体   中英

swift get final array from a completion block

I have a completion block that is returning an Assync array from Firebase, the problem Im having is that the single array is printing each array as it retrieve them I only want to retrieve the final array when it is complete. How can i achieve this?

this is the result being printed

[["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)
        }
    })
}

You are calling your completion handler inside the for loop. Make sure to iterate over the data, do your logic first and finish it only when you have your userInfo array ready.

Your callback for .observeEventType(.Value, will look like the following:

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)

And your completion handler will only print the array passed in the completion handler.

currentIhelprInfo { (result) in
    print(result)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM