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

独自空忆成欢 提交于 2020-01-01 18:52:08

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/45168993/how-can-i-observe-firebase-child-value-changes-in-multiple-nodes-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!