Mariah Mariah - 3 months ago 10
Swift Question

Creating users in new Firebase and Swift

I'm trying to make a register view, where the users can register through email, password, username, phone number and city.

Here's the code for creating the users through email and password:

@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)
}
}

})
}


the question is how can I add the other values like username to firebase dashboard?

in the previous version of firebase I was creating a dictionary then use the setValue function!
But in the new firebase how can I do that?

Answer

For storing data in user's respective 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
                    ])
     }
  })
}

Your JSON tree will look something like this :-

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

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