在新的Firebase和Swift中创建用户

时间:2016-08-16 08:56:07

标签: swift xcode firebase

我正在尝试创建一个注册视图,用户可以通过电子邮件,密码,用户名,电话号码和城市进行注册。

以下是通过电子邮件和密码创建用户的代码:

 @IBAction func Register(sender: AnyObject) {


   guard let email = EmailTextField.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) where !email.isEmpty else {
        print("Email is empty")
        return
             }

    guard let password = PasswordTextField.text where !password.isEmpty
        else {
    print("Password is empty")
        return
             }
    guard let repeatPassword = RePasswordTextField.text where !repeatPassword.isEmpty
        else {
             print("Repeat Password is empty")
            return
             }

    guard password == repeatPassword else {
    print("Password does not match")
        return
    }

    FIRAuth.auth()?.createUserWithEmail(EmailTextField.text!, password: PasswordTextField.text!, completion: { user, error in
        if let error = error {
        print(error)
        } else {
            if let user = user {
            print(user)
            }
        }

    })
}

问题是如何将其他值(如username)添加到firebase仪表板?

在以前版本的firebase中我创建了一个字典然后使用setValue函数! 但在新的火力基地我该怎么做?

1 个答案:

答案 0 :(得分:2)

用于在用户的uid

中存储数据
 let ref = FIRDatabase.database().reference()  //Global Variable
 ... 
 ...
 @IBAction func Register(sender: AnyObject) {


guard let email = EmailTextField.text?.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) where !email.isEmpty else {
    print("Email is empty")
    return
         }

guard let password = PasswordTextField.text where !password.isEmpty
    else {
print("Password is empty")
    return
         }
guard let repeatPassword = RePasswordTextField.text where !repeatPassword.isEmpty
    else {
         print("Repeat Password is empty")
        return
         }

guard password == repeatPassword else {
print("Password does not match")
    return
}

FIRAuth.auth()?.createUserWithEmail(EmailTextField.text!, password: PasswordTextField.text!, completion: { user, error in
    if let error = error {
    print(error)
    } else {
        ref.child("UserProfile").child(user!.uid).setValue([
                    "username" : usernameTextField.text!,    //Or whatever way you are extracting these information
                    "phoneNumber" : phoneNumberTextField.text!,     //Or whatever way you are extracting these information
                    "city" : cityTextField.text!       //Or whatever way you are extracting these information
                    ])
     }
  })
}

您的JSON树将如下所示: -

{UserProfile : {
   user_ID_1 :{
          userName : "Tim",
          phoneNumber : +1(23)....,
          city : "Los Angeles"    
               }

   user_ID_2 :{
          userName : "Hnery",
          phoneNumber : +1(073)....,
          city : "New York"    
               }
       }
}