我有一个 ref,我使用 observeEventType
来查询数据。但由于用户删除,ref 中可能没有数据。我使用 snapshot.exists()
测试它。在下面的情况下 snapshot.exists()
将返回 false/no
。因为它是假的,所以我想做点别的,但代码永远不会运行
当 snapshot.exists() 返回 false/no 时,我该如何做其他事情?
//there is no data at levelTwo so there's nothing to observe
let levelTwoRef = dbRef.child("players").child("uid").child("levelTwo")
levelTwoRef.observeEventType(.ChildAdded, withBlock: {
(snapshot) in
if snapshot.exists(){
if let dict = snapshot.value as? [String:AnyObject]{
let power = dict["power"] as? String
let score = dict["score"] as? String
}
//this will never run because the data has been deleted
} else{
do something else as an alternative //why isn't this running??
}
})
最佳答案
Firebase 有一个 .hasChild
函数,您可以在 child
上运行它来查看它是否存在:
func hasChild(_ childPathString: String) -> Bool
它接受一个 child
作为 String
参数并返回 True
或 False
取决于它是否存在不是。
检查 child 是否存在的方法是在您要查找的 child 之前先设置 child 的路径。在问题的情况下, child 要寻找的是 "levelTwo"
,而之前的 child 是 uid
:
//there is no data at levelTwo so there's nothing to observe
let levelTwoRef = dbRef.child("players").child("uid").child("levelTwo")
假设您知道 uid ref 确实存在,为 uid ref 而不是 levelTwo ref 设置一个常量
// uid path definitely exists
let uidRef = dbRef.child("players").child("uid")
在 uid ref 上运行 .value
并在回调内部检查 levelTwo ref 是否存在:
uidRef?.observeSingleEvent(of: .value, with: {
(snapshot) in
if snapshot.hasChild("levelTwo"){
// true -levelTwo ref Does exist so do something
}else{
// false -levelTwo ref DOESN'T exist so do something else
}
}
关于ios - 当 snapshot.exists() 返回 false 时怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42892486/