我的数据模型如下:

allcomments
|__$comment_id_5
         |__post_id: <post_id_5>



uid
|
|__activity
     |__comments
            |__$random_activity_id
                       |__post_id : <post_id_5> //ref to post_id_5 in allcomments
                       |__comment_id : <comment_id_5> // ref to comment_id_5 in allcomments

我的目标:检查uid的用户是否对帖子发表了评论。如果那个人有,那么我可以继续,否则他会在屏幕上显示其他东西。在尝试下面的查询时,只有快照存在时,才能获得回调,而不是其他情况。
FBDataservice.ds.child("allcomments").queryOrdered(byChild: "post_id").queryEqual(toValue: "post_id_5").observeSingleEvent(of: .ChildAdded) { (snapshot) in
        if let data = snapshot.value as? DataDict {
            let comment = Comment(comId: snapshot.key , comData: data)
            self.checkUserHasResponded(completion: { (hasResponded) in
                if !hasResponded {
                    // Never returns it there is nothng
                    print("You gotta respond first")
                } else {
                    //this part does work
                    print("Welcome to seeing everything")
                }
            })
        }
    }


func checkUserHasResponded(completion: @escaping (Bool) -> ()) {
    FBDataservice.ds.REF_USERS.child(uid).child("activity/comments").queryOrdered(byChild: "post_id").queryEqual(toValue: "post_id_5").observeSingleEvent(of: .value) { (snapshot) in
        snapshot.exists() ? completion(true) : completion(false)
    }
}

我甚至试着用这种方式调整架构并以不同的方式查询它,但仍然没有任何工作,程序的行为与上面所述完全相同。
uid
|
|__activity
     |__comments
            |__post_id_5 : comment_id_5

并运行此查询:
func checkUserHasResponded(completion: @escaping (Bool) -> ()) {
    FBDataservice.ds.REF_USERS.child(uid).child("activity/comments").observeSingleEvent(of: .value) { (snapshot) in
        snapshot.hasChild("post_id_5") ? completion(true) : completion(false)
    }
}

我试着把.childAdded改成.value。它给出了同样的精确结果。也尝试过将.observeSingleEvent(of:)更改为.observe()。但没什么帮助。我不知道到底怎么了。在这里检查大量答案,没有帮助。我到底在看什么。谢谢你的帮助。

最佳答案

使用.Valut而不是.CythAdvices,这样就可以将该闭包称为快照是否存在,只是一个快速测试表明它是有效的。

func checkUserHasResponded() {
    let uid = "uid_0"
    let commentsRef = dbRef.child(uid).child("activity").child("comments")
    commentsRef.queryOrdered(byChild: "post_id")
               .queryEqual(toValue: "post_5")
               .observeSingleEvent(of: .value) { snapshot in
        if snapshot.exists() {
            print("post exists")
        } else {
            print("post not found")
        }
    }
}

如果您的结构不包含存在的PySyID子值,则输出为
post not found

所以这个答案适用于最新的问题。如果查询所使用的节点不存在,因为查询正在使用,则关闭中的代码将不会运行。
FBDataservice.ds.child("allcomments").queryOrdered(byChild: "post_id")
                                 .queryEqual(toValue: "post_id_5")
                                 .observeSingleEvent(of: .childAdded) { (snapshot) in

如果更改为.Valk,则返回,并且如果节点存在,则在闭包中运行代码。记住你会想用
snapshot.exists()

如果没有,那就等于没有。

关于ios - Firebase查询不返回任何数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56312915/

10-09 06:40
查看更多