如何在Swift中的多个节点中观察Firebase子值的变化? [英] How can I observe Firebase child value changes in multiple nodes in Swift?
问题描述
我的Firebase数据库中有一个用户"节点.其中的每个用户都有一个带有uid的根.每个用户的属性之一是坐标".我想为所有用户观察这些坐标中的任何变化.我几乎需要像这样的东西:
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
我的结构如下:
-
用户
users
-
abcdefghijklmnop
abcdefghijklmnop
-
坐标:"12.345,12.345"
coordinates: "12.345,12.345"
其他道具
qrstuvwxyz
qrstuvwxyz
-
坐标:"34.567,34.567"
coordinates: "34.567,34.567"
其他道具
因此,我正在寻找坐标值更改的所有用户的全局通知.
So I'm looking for a global notification for any user whose coordinates value changes.
我是否需要遍历userDatabaseReference中的所有子项,并为每个子项设置观察者?然后,无论何时添加或删除用户,都重新设置一次?
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?
推荐答案
您可以观察整个用户结构,然后使用快照确定坐标是否为已更改的元素
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
})
您还可以做的是:
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
}
因此,每当您添加一个新子项时,它都会自动为其设置观察者,但是它们都被推送到了同一个函数foundSnapshot
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
这篇关于如何在Swift中的多个节点中观察Firebase子值的变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!