【问题标题】:Firebase Swift .exist() not workingFirebase Swift .exist() 不工作
【发布时间】:2016-11-23 04:21:12
【问题描述】:

您好,我在 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 并确保此人尚未关注此人。这是我试图解释的数据结构的快照:

【问题讨论】:

    标签: swift firebase firebase-realtime-database


    【解决方案1】:

    我可以提出一个替代方案吗?此解决方案将值读取为有问题的位置。这里最大的好处是没有查询开销。

    假设我们想看看我们是否关注 frank,如果不是,就关注他。

    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
    

    【讨论】:

    • 我认为这只会读取一个值,我想检查下面的所有 autoId。请查看我对问题的编辑
    • @TNeate 是的,你是对的,它只读取一个值。但这就是你想要做的,对吧?您问题的动态发生了变化,所以我在答案中添加了一些内容,但这个概念仍然有效......
    • 非常感谢!你说得对,我的数据结构设置不正确
    【解决方案2】:

    我认为您的查询可能不是工作用户InfoCenter.userId 可能是一个可选的强制解包,看看是否返回快照。

    【讨论】:

    • 不,抱歉,不是这样,我已经检查了 url 和它的好。 InfoCenter.userId 不是可选的
    • 当您print(snapshot) 时,结果是什么同时查看firstTextField.text 这可能是一个可选的,这可能是您总是收到false 的原因
    • 打印快照获取:Snap (following) null
    • 文本不是可选的
    • 问题出在你的查询上
    猜你喜欢
    • 2014-09-17
    • 2017-02-13
    • 1970-01-01
    • 2018-03-07
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-31
    相关资源
    最近更新 更多