Roggie
Roggie

Reputation: 1217

How to check if a Firebase DB node value is true using swift?

I have the following Firebase DB structure (see pic) which is created when a user sends a compliment to another user.

  1. The compliment is saved under compliments with an auto-generated id
  2. The compliment.key is also saved under users-compliments, under senderID/receiverID/then the "complimentID":"boolean" pair to indicate if it is "active"

I wish to check if an "active" compliment exists before being allowed to send another one to the same user.

But the following query results in a null output even though there is a child node with a value of 1.

What am I doing wrong here?

Query:

REF_USERS_COMPLIMENTS.child(currentUid).child(forId).queryEqual(toValue: "1").observeSingleEvent(of: .value) { (snapshot) in
        print("snap: \(snapshot.value)")
    }

Console output:

snap: Optional(<null>)

enter image description here

Upvotes: 0

Views: 286

Answers (2)

Andr&#233; Kool
Andr&#233; Kool

Reputation: 4978

When using queryEqual() you have to combine it with an queryOrderedBy. In your case it would be queryOrderedByValue() because you want to compare the value:

REF_USERS_COMPLIMENTS.child(currentUid).child(forId).queryOrderedByValue().queryEqual(toValue: "1").observeSingleEvent(of: .value) { (snapshot) in
    print("snap: \(snapshot.value)")
}

More information about this can be found in the docs.

Upvotes: 1

Dani
Dani

Reputation: 3637

Try this:

REF_USERS_COMPLIMENTS.child(currentUid).child(forId).observeSingleEvent(of: .value) { (snapshot) in
       print("snap: \(snapshot.value)")
       if let _ = snapshot.value as? NSNull {
         // do your thing
       }
 }

Upvotes: 0

Related Questions