ios - 当 snapshot.exists() 返回 false 时怎么办?

标签 ios swift firebase firebase-realtime-database

我有一个 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??
        }
    })

enter image description here

最佳答案

Firebase 有一个 .hasChild 函数,您可以在 child 上运行它来查看它是否存在:

func hasChild(_ childPathString: String) -> Bool

它接受一个 child 作为 String 参数并返回 TrueFalse 取决于它是否存在不是。

检查 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/

相关文章:

ios - Xcode 6 Simulator 使用 x86_64 吗?

ios - 快速使用 ReactiveCocoa

swift - 如何删除 Firestore 字典值?

java - 让 ValueListener 只发生一次

ios - 隐藏键盘时隐藏快捷方式栏 ios(Ipad)

ios - iOS UI 以什么帧速率运行动画?

swift - 处理应用程序创建的一次性不可变数据

Swift 4.2 改进算法中的 "O"成本

ios - 将 AVI 视频转换为 MP4 视频(用于在 iOS 上播放)

javascript - 为什么我的 messaging.getToken() 在 firefox 中有效但在 chrome 中无效?