6

My View Contollers Login -> Main Menu -> A -> B -> C -> D

How do i dimiss all view controllers and go back to main menu

For Logout from my view controllers I am doing the following which takes back to Login

func logout{

    self.view.window!.rootViewController?.dismissViewControllerAnimated(false, completion: nil)
 }

Now what i am doing is this

class AppDelegate: UIResponder, UIApplicationDelegate {
     var viewControllerStack: [BaseViewController]!
}

override func viewDidLoad() {
    super.viewDidLoad()
    super.appDelegateBase.viewControllerStack.append(self)  
}

func go_To_MainMenu(){
    var countOfNumberOfViewCOntrollers = self.appDelegateBase.viewControllerStack.count 

        switch countOfNumberOfViewCOntrollers{

             self.presentingViewController?.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
            break;
        case 2:

            self.presentingViewController?.presentingViewController?.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
            break;
   }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Cloy
  • 2,141
  • 23
  • 32
  • Are you using segues? If so, use an [unwind segue](https://stackoverflow.com/questions/12561735/what-are-unwind-segues-for-and-how-do-you-use-them) – Paulw11 Jul 13 '17 at 08:31

6 Answers6

8

If your MainMenu VC always comes AFTER your Login VC, you could simply use the same method:

To MainMenu:

self.view.window!.rootViewController?.presentedViewController?.dismissViewControllerAnimated(true, completion: nil)
Pochi
  • 13,391
  • 3
  • 64
  • 104
1

Instead of presenting/dismissing you can use UINavigationController to push/pop view controllers. That way you can use UINavigationController's popToViewController(_:animated:) which can pop to any view controller in navigation stack.

mag_zbc
  • 6,801
  • 14
  • 40
  • 62
1

You can use Unwind Segue if MainMenu isn't your rootViewController. Look at this article, hope it will help. Unwind Segue with Swift

Norolim
  • 926
  • 2
  • 10
  • 25
1

Swift 5

This works for me

var presentingViewController = PresentingViewController()
self.dismiss(animated: false) {
    presentingViewController.dismiss(animated: false, completion: nil)
}
0

Use unwind segue instead of using RootViewController. Using unwind you can go back to any ViewController. DismissViewController always send the controller out from NavigationController.

amit
  • 387
  • 2
  • 10
0

This worked for me,

self.view.window!.rootViewController?.presentedViewController?.dismiss(animated: true, completion: nil)

El_boogy
  • 145
  • 4