首页 文章

如何在注册时向Firebase数据库添加用户名?

提问于
浏览
0

登录后,我希望我的应用程序在Firebase数据库中创建一个新字段,其中包含以用户名命名的子项 .

if let email = emailField.text, let pass = passwordField.text {

        // Check if it's sign in or register
        if isLogin {
            // Sign in the user with Firebase
            Auth.auth().signIn(withEmail: email, password: pass, completion: { (user, error) in

                // Check that user isn't nil
                if let u = user {
                    // User is found, go to home screen

                    self.ref?.child(email).childByAutoId().setValue("1")
                    self.performSegue(withIdentifier: "goHome", sender: self)
                    print("yes")
                }

当我尝试这样做时,它给出了一个名为 SIGABART 的错误,我认为这与错误连接正确无关 .

然而,如果我删除这一行:self.ref?.child(email).childByAutoId() . setValue(“1”)

或者将 email 字段更改为 "test" 之类的随机字符串,它可以正常工作并显示在Firebase中 .

4 回答

  • 0

    如果我没记错的话,你不能在节点名称中使用符号 @ . 这是第一个问题 . 你可以做另一件事,我认为更好,方式:

    你需要创建用户来反对:

    /users/uid from created FIRUser.
    

    您可以通过以下步骤执行此操作:

    例如,您的注册页面将包含3 UITextFieldsuserEmailuserLoginuserPassword .

    // *1* Create user
    FIRAuth.auth()!.createUser(withEmail: userEmail.text!,
                                 password: userPassword.text!)
      { user, error in
         if error == nil {
            // *2* Then log him in
            FIRAuth.auth()!.signIn(withEmail: self.userEmail.text!,
                                   password: self.userPassword.text!)
            { result in
               // *3* Create new user in database, not in FIRAuth
               let uid = (FIRAuth.auth()?.currentUser?.uid)!
               let ref = FIRDatabase.database().reference(withPath: "someStartPart/users").child(uid)
               ref.setValue(["uid": uid, "email": userEmail.text!, "login": userLogin.text!, "creationDate": String(describing: Date())])
    
               self.performSegue(withIdentifier: "fromRegistrationToMainPage", sender: self)
            }
         } else {
            print("\(String(describing: error?.localizedDescription))")
         }
      }
    

    像这样 . 希望能帮助到你 .

  • 0

    Firebase Auth不允许您存储此类值 . 您需要将其保存到Firebase数据库或其他服务中 . 例如在Firebase数据库中:

    userRef.setValue("username123")
    
  • 0

    您应该在数据库中保存用户名值 . 像这样的东西:

    FIRdatabase.database().reference().child("yourchildname").updateChild(u)
    

    (我在手机上,所以通话可能不是那样,但应该非常接近)

    干杯 .

  • 0

    斯威夫特4:

    //***** for realTime database
            let ref = Database.database().reference(fromURL: "https://add your project URL")
            let userRef = ref.child("users").child(user.user.uid)
            let values = ["Email": email, "UserName": userName] //userName is the name of textField
    

相关问题