需要观察我的 Firebase 数据库 中的一个节点(如果它存在)。
我使用的代码是这样的:
var COLOR_REF = Database.database().reference().child("Colors")
self.COLOR_REF.child(id).observe(.childAdded) { (snapshot) in
let key = snapshot.key
Api.Post.getMyPosts(withId: key, completion: { (post) in
completion(post)
})
}
id 可能存在也可能不存在... 我需要的是执行观察
if child(id) exist else do something else.
有没有办法在一次观察中做到这一点,或者我需要观察 COLOR_REF
然后如果 id 存在观察 child ?
谢谢! - - - - - - - - - - - - - - - 更新 根据图片可以说我的 id 是:
D7CGNLehdjksnjkdsiwgqauymj3 我这样观察:
COLOR_REF.child(id).observe(.childAdded) { (snapshot) in
if snapshot.exists() {
print("YES")
} else {
print("No")
}
let key = snapshot.key
Api.Post.getMyPosts(withId: key, completion: { (post) in
completion(post)
})
}
因此假设在我执行观察时 id 控制台不会打印“YES”或“NO”。所以基本上它似乎永远不会进入观察者
----------------------------第二次更新 这是我现在的做法:
func observeFeed(withUserId id: String, completion: @escaping (Post) -> Void, isEmpty: @escaping () -> Void) {
COLORS_REF.observe(.value) { (snapshot) in
if snapshot.hasChild(id) {
self.COLORS_REF.child(id).observe(.childAdded) { (snapshot) in
let key = snapshot.key
Api.Post.getMyPosts(withId: key, completion: { (post) in
completion(post)
})
}
} else {
isEmpty()
}
}
}
就像这样工作......我确实在完成后将所有内容存储在一个数组中。我的问题是,如果这是用户第一次登录,那部分数据库将为空。 所以我想知道是否有一种方法可以在不使用双重观察者的情况下实现这一点......
最佳答案
您可以通过检查 snapshot.exists() 在观察中是否返回 true 或 false 来检查 id 是否存在,如下所示:
self.COLOR_REF.child(id).observe(.childAdded) { (snapshot) in
if snapshot.exists() {
//the id is valid
}
else {
//the id is not there. do something else
}
}) { (error) in
print(error.localizedDescription)
//snapshot might have been nil, or there was no id or security rules denied permission to read. do something else.
}
关于ios - Swift 3 和 Firebase 观察 Child 是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47218041/