Home > Software design >  How to programmatically segue after successful authentication with Firebase?
How to programmatically segue after successful authentication with Firebase?

Time:04-23

I'm just starting to code with Swift and I need help! I have authentication with firebase with email, I would like that after this login to show another view controller, I'm confused because I don't know how can I use the prepare to segue in this case. Where I need to add and how.

Thanks

My code is here.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let lvc = storyboard?.instantiateViewController(withIdentifier: "homeViewController") as? homeViewController
    self.navigationController?.pushViewController(lvc!, animated: true)
    
}

@objc private func didTapButton() {
    print("Continue Button Password")
    guard let email = emailField.text, !email.isEmpty,
          let password = passwordField.text, !password.isEmpty else {
        print("Missing field data")
        return
    }
    
    
    FirebaseAuth.Auth.auth().signIn(withEmail: email, password: password, completion: { [weak self] result, error in
        guard let strongSelf = self else {
            return
        }
        
        //            guard error == nil else {
        //                //show account creation
        //                strongSelf.showCreateAccount(email: email, password: password)
        //                return
        //            }
        print("You have signed in")
        strongSelf.label.isHidden = true
        strongSelf.emailField.isHidden = true
        strongSelf.passwordField.isHidden = true
        strongSelf.Button.isHidden = true
        
        strongSelf.emailField.resignFirstResponder()
        strongSelf.passwordField.resignFirstResponder()
        
    })
}

CodePudding user response:

The prepare(for:sender:) is not correct. That method is for passing data to the segue.destination view controller, not for initiating a push or whatever. E.g., if your destination view controller was a FooViewController and you wanted to set the bar property in order to pass some data from the current view controller to FooViewController, you would:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? FooViewController {
        destination.bar = ...
    }
}

But if you don't need to pass any data to the destination view controller, then no prepare(for:sender:) is needed.


In answer to the titular question, if your storyboard has a segue, give that segue an identifier, and then to initiate it programmatically, you would do:

storyboard?.performSegue(withIdentifier: "xxx", sender: self)
  • Related