ios - Firebase 查询(在 Swift 中)以在应用程序的所有用户中查找特定值

标签 ios swift search firebase firebase-realtime-database

我对 Swift 和 Firebase 比较陌生,我正在寻找一种查询 Firebase 数据库以查找特定值的方法。在我正在开发的应用程序的上下文中,当用户注册时,他必须选择一个用户名,我们想在数据库中验证没有其他用户已经拥有所选的用户名。我的数据库结构如下:

Image of DB structure

假设我正在应用程序中注册,我希望我的用户名是“mike”。我希望应用程序在数据库中的所有“用户名”字段中进行搜索,以检查“mike”是否已被占用,但我的 Firebase 代码不起作用:

let queryRef = FIRDatabase.database().reference().child("users")
    queryRef.queryOrdered(byChild: "username")
        .queryEqual(toValue: self.username.text)
        .observeSingleEvent(of: .value, with: { snapshot in
            if snapshot.exists()
            {
                print(snapshot)
            }
        })

“快照输入”之后的所有内容甚至都不会执行(它会跳过指令集)。现在,在进行实际检查之前,我只是在测试尝试打印“快照”值,但它从未被打印出来。

我这样设置我的数据库规则,因为任何试图查询它的人都需要访问“用户名”键:

{
  "rules": { 
    "users": {
      "$uid": {

        "email": {
          ".read": "$uid === auth.uid",
          ".write": "$uid === auth.uid",  
        },
        "username": {
          ".read": true,
          ".write": "$uid === auth.uid",  
        }

      }
    }     
  }  
}

对我而言,除了“用户名” key 外,所有内容都保密,这对我来说很重要。在此示例中,为了简单起见,我只有“电子邮件”和“用户名”键,但在我的实际应用程序中,我有更多(名字、姓氏、出生日期、电话号码等)

在这一点上的任何帮助将不胜感激。 非常感谢

最佳答案

我认为这是不可能的。

来自 Firebase 文档:

Rules are applied in an atomic manner. That means that a read or write operation is failed immediately if there isn't a rule at that location or at a parent location that grants access. Even if every affected child path is accessible, reading at the parent location will fail completely.

在您的情况下,当您尝试按 username 进行过滤但父节点 users 没有规则时,您将无法完成过滤PERMISSION_DENIED 失败。

您可以访问 users/a_valid_uid/username,因为整个路径都是可访问的。

解决此问题的方法是创建一个仅包含用户名的单独节点,并将其提供给公众阅读。

您可以查看有关 Firebase 规则的完整文档 here .

注意:您可以使用 Firebase 规则模拟器在部署之前测试您的规则。

关于ios - Firebase 查询(在 Swift 中)以在应用程序的所有用户中查找特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42799615/

相关文章:

ios - 弹性布局不适用于 subview Controller

ios - 从 json 循环数组

android搜索多个关键字

algorithm - 进行数据库查询 "Intelligent"?

java - Hibernate Search 3.1.1 - 如何以任意顺序搜索字段中同一短语中的多个单词

iphone - 单击上一个按钮后如何在单选按钮上保持选择

iphone - ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering 的代码示例?

ios - 尝试获取 UIImage 的当前值

iphone - NSInvalidArgumentException ||发送到实例的无法识别的选择器

ios - 适用于 twilio 的 AlamoFire