Search code examples
iosswiftfirebasefirebase-realtime-databaseobservers

How can I observe Firebase child value changes in multiple nodes in Swift?


I have a "users" node in my Firebase database. Each user in it has a root with a uid for it. One of the properties of each user is "coordinates". I want to observe any change in any of those coordinates for all users. I almost need something like:

usersDatabaseReference.child("*").child("coordinates").observe(.value, with: { (snapshot) in 

My structure looks like this:

  • users

    • abcdefghijklmnop

      • coordinates: "12.345,12.345"

      • other props

    • qrstuvwxyz

      • coordinates: "34.567,34.567"

      • other props

So I'm looking for a global notification for any user whose coordinates value changes.

Do I need to loop through all children in my userDatabaseReference and set observers for each? And then any time a user is added or removed, set it all up again?

You can see why I'd like to use a wildcard. How should I approach this?


Solution

  • You could just observe the users structure as a whole, then use the snapshot to determine if the coordinate is the element that has changed

    usersDatabaseReference.child("users").observe(.childChanged, with: { (snapshot) in
            //Determine if coordinate has changed
     })
    

    What you could also do is :

    func observeChildAdded(){
        usersDatabaseReference.child("users").observe(.childAdded, with: { (snapshot) in
            //Get the id of the new user added
            let id = "123"
            self.usersDatabaseReference.child("users").child(id).observe(.childChanged, with: { (snapshot) in
                self.foundSnapshot(snapshot)
            })
        })
    }
    
    func foundSnapshot(_ snapshot: DataSnapshot){
        let idChanged = snapshot.key
        //Process new coordinates
    }
    

    So that whenever you add a new child it automatically sets up an observer for it, but they all get pushed to the same function foundSnapshot