Hi, I just read this excellent tutorial on Firebase and got stuck afterwards trying to add additional user data in the database when a new user is created.
This is where I am at right now:
let saveAction = UIAlertAction(title: "Registrera", style: .default) { _ in
let userNameField = alert.textFields![0]
let emailField = alert.textFields![1]
let passwordField = alert.textFields![2]
Auth.auth().createUser(withEmail: emailField.text!, password: passwordField.text!) { user, error in
if error == nil {
Auth.auth().signIn(withEmail: self.textFieldLoginEmail.text!, password: self.textFieldLoginPassword.text!)
// This is where I add more user data to the database
let newUser = [
"username": userNameField.text!,
"email": emailField.text!,
"counter": 0] as [String : Any]
Auth.auth().addStateDidChangeListener() { auth, user in
if let user = user {
let newUserRef = Database.database().reference(withPath: "/users/\(user.uid)")
newUserRef.setValue(newUser)
}
}
}
}
}
Now, after trial and error:ing, this works, it adds username, email and counter to the database, but using addStateDidChangeListener() right after creating the user… it just feels like I am doing something wrong/non-optimal (as I am also using it in viewDidLoad, like in the tutorial). I just couldn’t figure out how to get a reference or the uid for the newly created user.
Any ideas/tips on how to add stuff in the database like this?