Vedant
Vedant

Reputation: 339

Swift: Presenting VC in completion handler of dismissal

I have the following ViewController (VC) flow:

SplashScreen/launch VC -> Login VC (on notification, present) -> SplashScreenVC -> Main VC

I want to avoid using an unwind segue because I will need to regularly re-authenticate the user regardless of current VC and so would much rather programatically 'present'.

The problem is, I am able to present and dismiss the SplashScreen VC (which is originally the root) but then cannot do the same for the Login VC without an error.

Code:

//in SplashScreen VC viewDidAppear

let loginVC = myStoryboard.instantiateViewController(identifier: "loginVC") as UIViewController
        loginVC.modalPresentationStyle = .fullScreen
        loginVC.modalTransitionStyle = .coverVertical

        //dismissal?
        self.dismiss(animated: true, completion: {
            self.present(loginVC, animated: true, completion: nil)
        })


//in loginVC selector function
let launchVC = myStoryboard.instantiateViewController(identifier: "launchVC") as UIViewController
        launchVC.modalPresentationStyle = .fullScreen
        launchVC.modalTransitionStyle = .coverVertical

        //check for top view controller (debugging)
        print("TOPVC at LoginVC: \(self.getTopVC()!)")

        //handle dismissal?
        self.dismiss(animated: true, completion: {
            self.present(launchVC, animated: true, completion: nil)
        })

WARNING:

Warning: Attempt to present <Slidr.LaunchScreenViewController: 0x15be0ef90> on <Slidr.LoginViewController: 0x15be6b510> whose view is not in the window hierarchy!

Warning: Attempt to present <Slidr.TestingViewController: 0x15db00ac0> on <Slidr.LaunchScreenViewController: 0x15bd06960> whose view is not in the window hierarchy!

Code runs fine if I don't dismiss the loginVC but I would like to avoid residue controllers over time.

I've tried to present from the top VC rather than 'self' but that doesn't seem to change anything.

Any help would be much appreciated.

Upvotes: 0

Views: 1035

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

As error says you need to present a vc from a 1 that's currently dismissed , so instead do

self.dismiss(animated: true, completion: {
   (UIApplication.shared.delegate as! AppDelegate).window?.rootViewController = loginVC
}

Another way also is to embed rootVC inside a navigationController and do

self.navigationController?.setViewControlls([loginVC],animated:true)

Upvotes: 2

Related Questions