简体   繁体   English

如何使用用户输入为Firebase中的孩子命名?

[英]How can I use user input to name a child in Firebase?

I'm trying to create a simple user database on Firebase for iOS. 我正在尝试在iOS的Firebase上创建一个简单的用户数据库。 I have two textfields, one that takes the user's email address, and the other that takes the user's password. 我有两个文本字段,一个使用用户的电子邮件地址,另一个使用用户的密码。 I want the email to be the user's uid. 我希望电子邮件成为用户的uid。 I try to accomplish this by creating a variable called "email" which I set equal to emailTextField.text! 我试图通过创建一个名为“ email”的变量来实现此目的,该变量设置为等于emailTextField.text! Then I implement the code that generates child(s) in Firebase, like so: 然后,我实现在Firebase中生成子代的代码,如下所示:

ref = Database.database().reference()

ref.child("users").child(email).setValue(true)

Here's my problem: creating a child and naming it using a variable, doesn't work. 这是我的问题:创建一个孩子并使用变量命名它不起作用。 I can do the following just fine: 我可以做以下事情:

ref.child("users").child("email")

but once I take away the quotation marks around "email" so that it becomes the variable, the program crashes. 但是一旦我删除了“电子邮件”周围的引号,使它成为变量,程序就会崩溃。 How can I use user input to name a child in Firebase? 如何使用用户输入为Firebase中的孩子命名?

Firebase node / document names do not support the same character set which email addresses support, for example, the . Firebase节点/文档名称不支持电子邮件地址支持的相同字符集,例如。 symbol in an email address would make the child name invalid. 电子邮件地址中的符号会使子名称无效。

If you tried setting a child as ref.child("users").child("xyz@xyz.xyz") you should see the same error. 如果尝试将子项设置为ref.child("users").child("xyz@xyz.xyz") ,则应该看到相同的错误。

If you absolutely need to use the email address as the node name, I recommend encoding the email in a way which is compatible with the firebase node name rules. 如果您绝对需要使用电子邮件地址作为节点名称,则建议以与Firebase节点名称规则兼容的方式对电子邮件进行编码。

Link to the rules 链接到规则

Edit: If you are using firebase auth, the normal pattern is too use the UID returned by the authenticated user object as the node name, not the email address entered from the textfield. 编辑:如果您使用的是Firebase身份验证,则正常模式也将使用经过身份验证的用户对象返回的UID作为节点名,而不是从文本字段输入的电子邮件地址。

A quick example: 一个简单的例子:

Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
  if let user = user {
        ref.child("users").child(user.uid).setValue(true)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM