I am new to firebase and I'm trying to learn how to create users. My problem is that when i use the createUserWithEmail completion block via a button, for some reason the unique identifier, the uid, is not generated. This prevents me from storing the associated username and password under the uid in the JSON tree. My code is as follows (I have defined databaseRef in a separate swift file as a global constant using "let databaseRef = FIRDatabase.database().reference()")
@IBAction func createAccount(sender: AnyObject) {
var username = usernameField.text
var email = emailField.text
var password = passwordField.text
if username != "" && email != "" && password != "" {
FIRAuth.auth()?.createUserWithEmail(email!, password: password!, completion: { (user, error) in
databaseRef.child("users/(user.uid)/username").setValue(username)
databaseRef.child("users/(user.uid)/password").setValue(password)
databaseRef.child("users/(user.uid)/uid").setValue(user?.uid)
})
} else {
print("please complete all fields")
}
}
I know the uid is not generated for two reasons. Firstly, when i run the above code and enter in values for each of my texts fields, the app crashes. Secondly, if i delete the code that deals with setting the values and replace it with print(user.uid), a value of nil is returned. What am i missing? I can understand that the uid is a very important part of creating a user.
***Here is the solution I came up with
@IBAction func createAccount(sender: AnyObject) {
var username = usernameField.text
var email = emailField.text
var password = passwordField.text
if username != "" && email != "" && password != "" {
FIRAuth.auth()?.createUserWithEmail(email!, password: password!, completion: { (user, error) in
if let user = FIRAuth.auth()?.currentUser {
databaseRef.child("users/\(user.uid)/username").setValue(username)
databaseRef.child("users/\(user.uid)/password").setValue(password)
databaseRef.child("users/\(user.uid)/email").setValue(email)
print(user.uid)
} else {
print("no user")
}
})
} else {
print("please complete all fields")
}
print(user)
and make sure it is returning the user info. – dylankbuckleyerror
object returned in the callback. It might have some nice information on whats happening. – adolfosrs