KoolKid
KoolKid

Reputation: 45

How do I stop a segue from going through programmatically in Swift?

Here is the code:

    @IBAction func loginTapped(_ sender: Any) {

    let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
    let password = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)

    Auth.auth().signIn(withEmail: email, password: password) { (result, error) in

        if error != nil {
            self.errorLabel.text = error!.localizedDescription
            self.errorLabel.alpha = 1
            print(error!.localizedDescription)
        }
        else {

            self.performSegue(withIdentifier: "loginSegue", sender: nil)

            print("User is signed in with Firebase.")
        }
    }
}

I have a segue, loginSegue, connected from the login button to the homeViewController. Within in the if error statement I would like to stop the segue from going through because the user has not signed in. The goal here is not allow the user to go forward if they get an error. Is there an "opposite" to the performSegue(withIdentifier: String, sender: Any?) ?

Upvotes: 0

Views: 1094

Answers (3)

Omer Tekbiyik
Omer Tekbiyik

Reputation: 4754

First , there is no "opposite" to performSegue(withIdentifier: String, sender: Any?).

But the issue is not about this. I think you wired the segue from the login button and gave it an identifier. If you wire a segue from a button directly the button is always going to execute that segue. Doing some operations in the button's action does not effect.

You need to wire a segue from FirstVc to SecondVc (not from the button) and then give the segue an identifier. Then, from the button's action you can check if there is no error and call performSegue(withIdentifier: String, sender:) passing your segue's identifier.

Upvotes: 1

Frankenstein
Frankenstein

Reputation: 16341

You could override the shouldPerformSegue(withIdentifier:,sender:) method and return false if the login fails and you don't want to perform the segue. Here's an example

override func shouldPerformSegue(withIdentifier identifier: String?, sender: Any?) -> Bool {
    if let ident = identifier {
        if ident == "YourIdentifier" {
            if loginSuccess != true {
                return false
            }
        }
    }
    return true
}

Upvotes: 2

MarekB
MarekB

Reputation: 686

I think your button is connected to perform segue in storyboard. So your button has two actions - one from storyboard to perform segue and second in your code. Just remove the connection from storyboard and connect only UIViewControllers not with your button.

Upvotes: 1

Related Questions