0

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

1 Answer 1

3

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.