How to get all results from a Firebase Query in one block

Question!

I'm having a hard time working with Firebase query results. With the following code:

     ref.queryOrderedByChild("gender")
        .queryEqualToValue("female")
        .observeEventType(.ChildAdded, withBlock: { snapshot in
        print("result: \(snapshot) ")
     })

The "result" is printed 3 times. I would expect a single array of all of the results (similar to a query on Parse) versus this being printed 3 separate times.

The end goal here is to append all of the results to an Array. However, I don't know how to do that, since I can't see any way of knowing how many elements will come back from the server.

I assume there must be something simple I am missing here.



Answers

It appears it was something simple I was missing. Changing the event type from .ChildAdded to .Value resolves the issue. Hopefully this will help someone else...

 var resultArray:[AnyObject] = []
         ref.queryOrderedByChild("gender")
            .queryEqualToValue("female")
            .observeEventType(.Value, withBlock: { snapshot in

                for item in snapshot.children{
                    resultArray.append(item)
                }
                print("Results Array: \(resultArray)")
                print("Results Array Count: \(resultArray.count)")

         })


This video can help you solving your question :)
By: admin