swift - Firebase Swift .exist() 不工作

标签 swift firebase firebase-realtime-database

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

enter image description here

最佳答案

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

假设我们想看看我们是否关注弗兰克,如果没有,就关注他。

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/

相关文章:

json - 如何使用 swift 与 MapKit 映射 JSON 对象

javascript - 循环访问 Firebase 数据库记录集合

android - 在 Android 中从数组中的 firebase 获取数据

ios - 尝试使用 Firebase 后端创建排行榜并对数据进行排序无法正确检索数据(Swift 4.2)

github - 在 Github 上使用 Firebase 数据库上传项目是否安全?

ios - Firebase:从嵌套的 Childs 中检索信息 (Swift 3)

javascript - 如何使用另一个用户插入的电子邮件发送通知,该用户使用 Cloud Functions for Firebase 请求通知?

ios - 如何修复 Xcode 中的 '_sqlite3_prepare_v3' 链接器错误

ios - CNContactViewController 在 contactImage fullscreenView 后隐藏导航栏

ios - 如何设置 UICollectionView 填充 UIEdgeInsets