Search code examples
iosswiftsegue

Perform Segue from App Delegate swift


I need to launch a view controller from the app delegate.

In the way you would perform a segue between view controllers.

I have an if statement that if true needs to show a view controller, this is in the app delegate.

How do I do this from the app delegate?


Solution

  • c_rath's answer is mostly right, but you don't need to make the view controller a root view controller. You can in fact trigger a segue between the top view on the navigation stack and any other view controller, even from the App Delegate. For example, to push a storyboard view controller, you could do this:

    Swift 3.0 and Later

    // Access the storyboard and fetch an instance of the view controller
    let storyboard = UIStoryboard(name: "Main", bundle: nil);
    let viewController: MainViewController = storyboard.instantiateViewController(withIdentifier: "ViewController") as! MainViewController;
    
    // Then push that view controller onto the navigation stack
    let rootViewController = self.window!.rootViewController as! UINavigationController;
    rootViewController.pushViewController(viewController, animated: true);
    

    Swift 2.0 and Earlier

    // Access the storyboard and fetch an instance of the view controller
    var storyboard = UIStoryboard(name: "Main", bundle: nil)
    var viewController: MainViewController = storyboard.instantiateViewControllerWithIdentifier("ViewController") as MainViewController
    
    // Then push that view controller onto the navigation stack
    var rootViewController = self.window!.rootViewController as UINavigationController
    rootViewController.pushViewController(viewController, animated: true)