ios - Swift 3 和 Firebase 观察 Child 是否存在

标签 ios swift firebase firebase-realtime-database

需要观察我的 Firebase 数据库 中的一个节点(如果它存在)。 enter image description here

我使用的代码是这样的:

 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/

相关文章:

ios - 在 iPad 的存储空间中存储 1000 多张图像

swift - 我试图将一个 sider 连接到变量 "Cannot invoke initializer for type "Int",并使用类型为 '(_)' 的参数列表"

swift - 使用 Swift 进行正向地理编码

ios - UIView.animate - Swift 3 - 完成

ios - 坚持在 Swift 和 MapKit 中使用 MKPinAnnotationView()

ios - NEVPNManager 实例显示为 nil

ios - 我可以在 Realm.IO 中使用 child 的主键作为 parent 的主键吗?

javascript - firebase 云函数 onFinalize 触发器没有预定义存储桶?

ios - 无法通过观察 Firebase 中的数据库引用来获取顶级节点的值

firebase - 在 Firebase 中执行扇出数据的事务