Famic Tech
Famic Tech

Reputation: 280

Swift - Firebase observer on .childchanged is not being recognized

Here is the code below, it will not get executed even if I change the child node called "tokens" in the Firebase via app or directly in Firebase!?

handle = ref.child("Users").child(uid).child("tokens").observe(.childChanged, with: { snap in

                print("Changed Token Count: ", snap.value!)

                if snap.value is NSNull {

                    // Child not found

                } else {

                    if (currTokenCount < snap.value as! UInt) {

                        print("Value increased....")

                    } else {

                        print("Value decreased....")

                    }

                }

            }) { (error) in

                print(error.localizedDescription)

            }

Upvotes: 1

Views: 534

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

I assume you have a data structure like this:

Users
  uid1
    tokens: "value of tokens"

If you want to listen for changes to token of a specific user in the above structure, use a .value listener:

handle = ref.child("Users").child(uid).child("tokens").observe(.value, with: { snap in

    print("Changed Token Count: ", snap.value!)

    if snap.value is NSNull {
        // Child not found
    } else {
        if (currTokenCount < snap.value as! UInt) {
            print("Value increased....")
        } else {
            print("Value decreased....")
        }
    }
}) { (error) in
    print(error.localizedDescription)
}

The .child*listeners are only used when you have child nodes undertokens`, like:

Users
  uid1
    tokens
      token1: "value of token1"
      token2: "value of token2"

Upvotes: 3

Related Questions