Search code examples
swiftstoryboardclosuresseguegrand-central-dispatch

Swift- Firebase authentication signIn function inside a presenting segue, how to use shouldPerformSegue to stop the segue from performing?


I wanted to use a storyboard segue(present modally) to present the new view controller but the verification inside shouldPerform function are Firebase Authorization function signIn but since the trailing closure directly return the compiler back, it returns false before signIn function can make any changes to the flag.

var shouldPerformSegue = false
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
    guard let email = loginemail.text, let pass = loginpassword.text, email != "", pass != "" else {
        return false
    }
    Auth.auth().signIn(withEmail: email, password: pass) { (result, error) in
        if let error = error{
            TWMessageBarManager().showMessage(withTitle: "invalid email or pass", description: error.localizedDescription, type: .error)
            self.shouldPerformSegue = false

        } else {
        self.shouldPerformSegue = true
        }
    }
    return shouldPerformSegue
}

My goal is to use a storyboard segue(particularly a non-custom segue) to solve this, is it possible?


Solution

  • Try using a Completion Handler

    func didUserLoggedInSuccessfully(success:@escaping (NSDictionary) -> Void)
        {
            Auth.auth().signIn(withEmail: self.emailTextField.text!, password: self.passwordTextField.text!) { (user, error) in
                if error == nil {
                    success(true)
                }
                else{
                    //Tells the user that there is an error and then gets firebase to tell them the error
                    success(false)
                }
            }
        }
    

    Usgae

    self.didUserLoggedInSuccessfully { (success) in
                if success {
                    /// Perform Segue
                }
                else{
                    /// Do not Perform
                }
            }