How can I retrieve all the keys from a child from Realtime Database?

I have issues trying to fetch the number (count) of how many keys my child has and to retrieve an array with all the keys.

Right now, I have 4 keys under the child "Notifications". Every time I try to retrieve the count of keys from that child, I don’t know why, Firebase is returning the integer 49. Sometimes it will give me 48 or 56. This makes 0 sense because even if somehow I was getting all the keys from all childs, I would still have more or less than what it shows me.

After I run my code, only the most recent key is also displayed on my text field and refuses to show me all the keys as intended.

This is my code:

func retrieveNotifications() {
    let databaseRef = Database.database().reference()
    let dataName = Auth.auth().currentUser!.uid
    let ref = databaseRef.child("User_Information").child("\(dataName)").child("Notifications")
    
    ref.observeSingleEvent(of: .value , with: { (snapshot) in
            for notifications in snapshot.children {
                let snap = notifications as! DataSnapshot
                let key = snap.key
                let value = snap.value
                let count = snap.key.count
                
                if count > 0 {
                    self.notificationNumber.isHidden = false
                    self.noNewNotificationsMessage.isHidden = true
                    self.notificationsText.isHidden = false
                    self.clearButton.isHidden = false
                    self.notificationNumber.text = "\(count) notifications"
                    self.notificationsText.text = "\(key)"
                } else {
                    self.notificationNumber.isHidden = true
                    self.notificationsText.isHidden = true
                    self.clearButton.isHidden = true
                    self.noNewNotificationsMessage.isHidden = false
                }
            }
        })
}

This is my child:

enter image description here

I have looked at the code for hours, any help is very appreciated, maybe I am not seeing something obvious.

I have tried to everything I could think of at this point. Nothing is working.

>Solution :

You’re:

  1. Reading the notifications of the user.
  2. Then looping over the notification.
  3. Then for each notification you determine the length of its key

If you want to determine the number of child nodes under Notifications, that’d be something like:

ref.observeSingleEvent(of: .value , with: { (snapshot) in
    let count = snapshot.childrenCount
    ...

Also see the reference documentation for the childrenCount property

Leave a Reply