你好,我在 swift 上使用 firebase,但 .exist() 有问题
我正在尝试查询并检查一个值,如果它存在,我什么也不做,如果不存在,我将它添加到列表中。我只是想避免以这种方式复制数据。继承人的代码:
InfoCenter.ref.child("users/\(InfoCenter.userId)/following").queryOrderedByValue()
.queryEqualToValue(firstTextField.text)
.observeEventType(.Value, withBlock: { snapshot in
if snapshot.exists(){
self.displayAlert("You already follow that person!", Title: "Whoops")
print(snapshot.value!)
} else {
InfoCenter.ref.child("users/\(InfoCenter.userId)/following").childByAutoId().setValue(TheId)
InfoCenter.ref.child("users/\(TheId)/followers").childByAutoId().setValue(InfoCenter.userId)
print(snapshot.value!)
}
})
所以对我来说一切看起来都是正确的,但是当它运行 snapshot.exist() 时总是返回 false 但是当我打印 snapshot.value 时!我得到 null 周围有箭头(我无法输入箭头,因为那时我认为它是一个标签)。所以我很困惑.. null 是如何被认为存在的?有人可以告诉我要更改什么来解决这个问题吗?谢谢!!
编辑: 需要明确的是,以下是用户列表。因此,以下是具有指向其他用户的链接的 autoId。上述查询的全部目的是通过 autoId 并确保此人尚未关注该人。这是我试图解释的数据结构的快照:
最佳答案
我可以推荐一个替代方案吗?此解决方案将值读取为有问题的位置。这里的一大好处是没有查询开销。
假设我们想看看我们是否关注弗兰克,如果没有,就关注他。
let ref = InfoCenter.ref.child("users/\(InfoCenter.userId)/following")
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
if let person = snapshot.value as? String {
if person == "frank" {
print("you are following frank: creeeeepy")
} else {
print("you are not following frank, follow him")
}
} else {
print("node doesnt exist")
}
})
这将直接读取值
users/some_user_id/following: "the value that's read (frank in this case)"
编辑:根据更新后的问题,“以下”节点应如下所示
users
your_uid
following
some_user_you_are_following_uid: true
another_user_you_are_following_uid: true
那么你只是检查路径是否存在
let ref = InfoCenter.ref.child("users/\(InfoCenter.userId)/following")
let theUserRef = ref.child("some_user_you_are_following_uid")
theUserRef.observeSingleEventOfType(.Value, withBlock: { snapshot in
关于swift - Firebase Swift .exist() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38472640/