Reece Kenney
Reece Kenney

Reputation: 2964

Firebase number of results that contain a value - iOS Swift

I have a fairly simple scenario whereby I am trying to get the number of users with a particular favorite color. For example, I would like to retreive the number of users that have a favorite color of 'Blue'.

enter image description here

The following code will get me the number of children nodes each user has which in this case is 4 (favoriteColor, displayName, email and provider). I would instead like to get the number of users that have a particular favorite color.

let ref = Firebase(url: "https://project.firebaseio.com/users")
ref.queryOrderedByChild("favoriteColor").queryEqualToValue("Blue").observeEventType(.ChildAdded, withBlock: { snapshot in
            print(snapshot.childrenCount)

    })

I am trying to keep a live count of the number of users with a particular favorite color via UILabel so I will update the label each time there is a change to the number of results.

Is there currently a way to do this?

Upvotes: 1

Views: 600

Answers (1)

Reece Kenney
Reece Kenney

Reputation: 2964

I solved this by changing .ChildAdded to .Value.

I also changed observeEventType to observeSingleEventOfType

let ref = Firebase(url: "https://project.firebaseio.com/users")
    ref.queryOrderedByChild("favoriteColor").queryEqualToValue("Blue").observeSingleEventOfType(.Value, withBlock: { snapshot in
    print(snapshot.childrenCount)

})

Hope this helps someone in future!

Upvotes: 1

Related Questions