首页 文章

Firebase Swift .exist()无效

提问于
浏览
0

您好我在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(我无法输入箭头,因为SO认为它是一个标签) . 所以我很困惑..如何认为null存在?有人可以告诉我要改变什么来解决这个问题吗?谢谢!!

编辑:要清楚以下是用户列表 . 因此,以下是autoId,它们与其他用户有链接 . 上述查询的全部目的是通过autoId并确保此人尚未关注该人 . 这是我试图解释的数据结构的快照:

enter image description here

2 回答

  • 0

    我认为您的查询可能无法正常工作用户 InfoCenter.userId 可能是一个可选的强制解包并查看是否返回快照 .

  • 2

    我能建议一个替代方案吗?此解决方案将值读取为相关位置 . 这里的好处是没有查询开销 .

    假设我们想看看我们是否遵循坦诚,如果没有,请跟随他 .

    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
    

相关问题