swift - 实时数据库 - 如何更改安全规则以检查用户名是否存在

标签 swift firebase firebase-realtime-database firebase-security

我正在尝试检查用户名是否已存在于数据库中。

这是我为此编写的代码..


 func textFieldDidEndEditing(_ textField: UITextField) {

        //check if username is already taken in the database
        let username = self.usernameTextField.text!
        let reference = Database.database().reference().child("activeUsernames")
        let query = reference.queryOrdered(byChild: "username").queryEqual(toValue: username)

        let banner = StatusBarNotificationBanner(title: " The username \(username) is not available.", style: .danger)

        let successBanner =  StatusBarNotificationBanner(title: "The username \(username) is available.", style: .success)

        query.observe(.value, with: { (DataSnapshot) in

            if DataSnapshot.exists() {

                print("Darn username already exists")
                banner.show()

            } else {
               print("Yes I can use this username")
                successBanner.show()



            }

        }, withCancel: nil)
    }

到目前为止,它的工作原理并不一致。有时,如果我输入一个已经存在的用户名,打印语句 "Yes I can use this username" 会在它明显已经被占用时出现,有时它会让我知道它已经被占用。我注意到我在控制台中得到了这条语句

Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ".indexOn": "username" at /activeUsernames to your security rules for better performance

我不确定这是否会导致检查不一致。但是我不太确定如何有效地更改或编辑安全规则。

如果有帮助的话,这是我的事件用户名的数据结构,只显示用户 uid 和与该 uid 关联的用户名..

- activeUsernames
 6GpUz3iLwmWdDrlMtf7tT0yAULw2
 username: 
 8sRfoqa4dKYzUKGdIZAtwE6NQZH2
 username: 
 SRY4xUmRMgXbLL7GfsxosF6sS1y2
 username: 

这里还有安全规则

 "rules": {
    ".read": true,
    ".write": true
  }
}

最佳答案

要删除该消息,请将您的规则更改为: 不要忘记用 ,

分隔它们
{
  "rules": {
    ".read": true,
    ".write": true,
    "activeUsernames": {
      ".indexOn": "username"
    }
  } 
}

这告诉 Firebase 服务器在 /activeUsernames 下的 username 上添加索引,这允许它在服务器上而不是在客户端上执行排序/过滤。

关于swift - 实时数据库 - 如何更改安全规则以检查用户名是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57300395/

相关文章:

swift - NSFetchRequest 按日期

ios - 如何从导航堆栈中删除 ViewController 并且没有返回它的选项-Swift

xcode - UISwitch 设置开/关图片

android - 不同的权限 Firebase Auth

swift - Firebase 实时数据库查询 Swift 中的两个 child

ios - 使用解析获取错误(代码 : 105, 版本 : 1. 17.2)

firebase - 从Firebase(DART/Flutter)获取ID数组

java - 自动更新类内的共享首选项

ios - Firebase queryOrderedByChild() 方法不提供排序数据

android - 回收站 View 中的数据未上传到 Firebase