OGeek|极客世界-中国程序员成长平台

标题: ios - Swift 3 和 Firebase 观察 child (如果存在) [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:16
标题: ios - Swift 3 和 Firebase 观察 child (如果存在)

需要观察我的 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()
        }
    }
}

就像这样工作......我确实在完成后将所有内容存储在一个数组中。我的问题是,如果这是用户第一次登录,那么数据库的那部分将是空的。 所以我想知道是否有一种方法可以在不必使用双重观察者的情况下实现这一目标......



Best Answer-推荐答案


您可以通过检查 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/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4