0

I have 2 records in my users table

enter image description here

This code below

let fcmTokenRef = Database.database().reference().root.child("users").child(id!).child("fcmToken")
fcmTokenRef.observe(DataEventType.value, with: { (snapshot) in
    print(">>",snapshot)
})

will print out the token of a child

enter image description here

How do I adjust my code to print all the tokens for all my children?

code-8
  • 54,650
  • 106
  • 352
  • 604

2 Answers2

1

You’re requesting a onetime read, hence you’re reading the data once. You need to use .childAdded

Try this:

let fcmTokenRef = Database.database().reference().child(“users”)
    fcmTokenRef.observe(.childAdded, with: { (snapshot) in
    print(">>",snapshot)
     guard let data = snapshot as? NSDictionary else {return}
     var each_token = data[“fcmToken”] as? String
     print(“all tokens: \(each_token!)”)
})

@puf says something very important: differences between child added and value firebase

The child_added event fires for each matching child under the node that you query. If there are no matching children, it will not fire.

excitedmicrobe
  • 2,338
  • 1
  • 14
  • 30
1

You can try

let fcmTokenRef = Database.database().reference().root.child("users").observe(DataEventType.value, with: { (snapshot) in 
      print(">>",snapshot)

      let dic = snapshot.value as! [String:[String:Any]]
      Array(dic.values).forEach { 
        let str = $0["fcmToken"] as! String
        print(str)
     }
})
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87