首页 > 解决方案 > 您如何检查 firebase 快照子项的值是 true 还是 false?

问题描述

JSON
switch
  uid
    switch : true
  uid2
    switch : false

我试过的不起作用

 @objc func didLongPress() {


    let databaseRef = Database.database().reference().child("switch").child(self.postID)
databaseRef.queryOrdered(byChild: "switch").queryEqual(toValue: "true").observeSingleEvent(of: .value) { (snapshot) in               
   print(snapshot)
           if snapshot.exists() {
               print("Address is in DB")
             } else {
               print("Address doesn't exist")
             }
             }}
//////note it picks up self.postID successfully so error is after that. print snapshot gives null

也试过

   let databaseRef = Database.database().reference().child("switch").child(self.postID).child("switch/\true")
    databaseRef.observeSingleEvent(of: .value) { (snapshot) in
            print(snapshot)
        if snapshot.exists() {
            print("Address is in DB")
          } else {
            print("Address doesn't exist")
          }
            }
}

所以理论上这应该是一个非常简单的基本任务。上述尝试中的第一个应该有效。没有权限错误,但控制台仅生成 null 作为快照打印。这太奇怪了。

如果我测试一个简单的快照以查看打印的内容.child(switch).child(self.postID).child(switch)- 它打印 1 表示真,0 表示假。所以这行得通。

编辑:我认为这是因为它在目标 c 函数中。我才意识到这一点。我在目标 C 中需要它,因为如果在长按上调用它,它使用目标 c 函数

标签: iosswiftfirebasefirebase-realtime-databasesnapshot

解决方案


Try:

(Change database child path as per your need.)

Database.database().reference().child("switch").child(self.postID).queryOrdered(byChild: "switch").queryEqual(toValue: true).observeSingleEvent(of: .value, with: { (snapshot) in
     if let dict = snapshot.value as? [String: AnyObject] {
         print("Address is in DB")
     } else {
         print("Address doesn't exist")
     }
}) { (error) in
     print(error.localizedDescription)
   }

推荐阅读