简体   繁体   中英

Viewcontroller crashes after being presented by another viewcontroller

For some reason, viewDidLoad() crashes with

fatal error: unexpectedly found nil while unwrapping an Optional value

in authViewController in my app while setting up the UI after it's being presented from another viewcontroller:

//authViewController
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        authState.addTarget(self, action: #selector(authStateChanged), for: .valueChanged)//<-- The place where it crashes

        emailInput.addTarget(self, action: #selector(emailPasswordTextChanged), for: .editingChanged)
        passwordInput.addTarget(self, action: #selector(emailPasswordTextChanged), for: .editingChanged)
        SignIn.addTarget(self, action: #selector(signInPressed), for: .touchUpInside)
        //Set actions

        infoView.layer.cornerRadius = 5
        SignIn.layer.cornerRadius = 5
        //UI setup
}

The Other View Controller:

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        FIRAuth.auth()?.addStateDidChangeListener({ (auth, user) in
            if user != nil {

            }
            else {
                print("pop")
                DispatchQueue.main.async {
                    self.present(authViewController(), animated: true, completion: nil)
                }
            }
        })
    }

Can anybody please tell me what and why it happened if you know?

Instead of presenting the ViewController like

self.present(authViewController(), animated: true, completion: nil)

Try presenting ViewController after instantiating it

let storyBoard = UIStoryboard(name: storyboardname, bundle: nil)
let authVC = storyBoard.instantiateViewController(withIdentifier: viewController Identifier) as? authViewController
self.present(authVC, animated: true, completion: nil)

I solved it by doing:

let authVC = self.storyboard?.instantiateViewController(withIdentifier: "authVC")
self.present(authVC!, animated: true, completion: nil)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM