I am struggling to get a performSegue working with my user signup page. When the createUser method is called, I want to create a user, and if this has been done successfully, I want to show an alert and then proceed to the login page using the signupToLogin segue.
I know that the performSegue must be called from the main thread as it involves UI elements, and I am trying to use DispatchQueue.main.async for this. However, ONLY my alert shows up. The performSegue part of my code is not executed. I have seen similar stuff on StackExchange (performSegue not working FireBase while checking the user is authenticated Swift 3/4) but could not use them to get my code working. Can someone help me out?
func createUser(emailID: String, password: String) {
Auth.auth().createUser(withEmail: emailID, password: password){ (authResult, error) in
guard let user = authResult?.user, error == nil else {
print(error!.localizedDescription)
self.displayOKAlert(title: "Error", message: "An error occurred. Could not sign up user.")
return
}
DispatchQueue.main.async {
self.displayOKAlert(title: "Success", message: "Successfully signed up user. Proceeding to login page.")
self.performSegue(withIdentifier: "signupToLogin", sender: self)
}
}
}
The problem is exactly because you're trying to present and alert and perform the segue at the same time. Both require UI changes and probably the View controller is not able to handle them together.
What you can do is change your displayOKAlert
function to have a completion that you'll pass when presenting the alert in it. Something like this:
self.present(alert, animated: true, completion: completion)
Where your completion is something like this:
{
DispatchQueue.main.async {
self.performSegue(withIdentifier: "signupToLogin", sender: self)
}
}
Also, you'll want to add a logic to dismiss your alert at some point, otherwise it'll stay there on top of your next view controller if your segue is pushing it.