Want to call method after firebase authentication is complete
Want to call method after firebase authentication is complete
func signUpPressed(){
guard let email = signupview.emailTextField.textField.text, let password = signupview.passwordTextField1.textField.text, let name = signupview.nameTextField.textField.text else{
return
}
Auth.auth().createUser(withEmail: email, password: password, completion: {(User, error) in
if error != nil{
print(error)
return
}
let ref = Database.database().reference()
let uid = User?.user.uid!
let userReference = ref.child("Users").child((uid)!)
let values = ["name": name, "email": email]
userReference.updateChildValues(values, withCompletionBlock: {(err, ref) in
if err != nil{
print(err)
return
}
print("User saved to firebase")
})
})
getUserInfo()
}
What I hope to achieve from this is to be able to store all the User's information after the user has been created in firebase. The problem is that the getUserInfo method gets executed before the print("User saved to firebase"). I have also learned that firebase is asynchronous, which means that the call always returns immediately, without blocking the code to wait for a result. The results come sometime later, whenever they’re ready. Now what I want to be able to do is to call a method AFTER the results "come in". How can I do that?
getUserInfo
print("User saved to firebase")
2 Answers
2
Asynchronous doesn't block the main thread and also doesn't prevent the method
getUserInfo()
from running before response returns , so you need to insert it inside the completion block of updateChildValues like this
updateChildValues
func signUpPressed(){
guard let email = signupview.emailTextField.textField.text, let password = signupview.passwordTextField1.textField.text, let name = signupview.nameTextField.textField.text else{
return
}
Auth.auth().createUser(withEmail: email, password: password, completion: {(User, error) in
if error != nil{
print(error)
return
}
let ref = Database.database().reference()
let uid = User?.user.uid!
let userReference = ref.child("Users").child((uid)!)
let values = ["name": name, "email": email]
userReference.updateChildValues(values, withCompletionBlock: {(err, ref) in
if err != nil{
print(err)
return
}
getUserInfo()
print("User saved to firebase")
})
})
}
Put the call to getUserInfo() inside the completion block that gets executed when the results are ready.
getUserInfo()
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.