Issue on dismissing a viewController to rootViewController

90 Views Asked by At

I am trying to dismiss a viewController to rootViewController while signOut. But the problem is that the viewController is not getting dismissed, It still remains in the same page itself. Below I have mentioned the code that I have used.

    let AppDel = UIApplication.shared.delegate as! AppDelegate
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let login = mainStoryboard.instantiateViewController(withIdentifier: "login")
    let nav = UINavigationController(rootViewController: login)
    AppDel.window!.rootViewController = nav
    AppDel.window?.rootViewController?.dismiss(animated: true, completion: nil)
    (AppDel.window?.rootViewController as? UINavigationController)?.popToRootViewController(animated: true)
    login.navigationController?.setNavigationBarHidden(true, animated: false)

Thanks in advance.

3

There are 3 best solutions below

1
On BEST ANSWER

Earlier, I have faced the same issue. I was fixed issue by performing all other operation after dismissing controller successfully.

Please refer below sample code. I am sure it will work for you.

    AppDel.window?.rootViewController?.dismiss(animated: true, completion: {
        (AppDel.window?.rootViewController as? UINavigationController)?.popToRootViewController(animated: true)
        login.navigationController?.setNavigationBarHidden(true, animated: false)    
    })
0
On
  • Why have you dismissed your navigation controller before calling popToRootViewController ?

AppDel.window?.rootViewController?.dismiss(animated: true, completion: nil)

  • Check if you are calling this from the main thread. Add your code inside this block:

    DispatchQueue.main.async {
        // TODO: Your code
    }
    
0
On

in the App delegate type a function that takes the new view controller and set it as root. than dismisses the old one.

func updateRootViewController(with viewController: UIViewController) {
        guard let oldViewController = self.window?.rootViewController else { return }
        UIView.transition(from: oldViewController.view, to: viewController.view, duration: 0.3, options: [.transitionCrossDissolve, .allowAnimatedContent]) { _ in
            self.window!.rootViewController = viewController
            self.window!.makeKeyAndVisible()
            oldViewController.dismiss(animated: false) {
                oldViewController.view.removeFromSuperview()
            }
        }
    }