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?
The app delegate is effectively the root object of your app, and it works in conjunction with UIApplication to manage some interactions with the system. Like the UIApplication object, UIKit creates your app delegate object early in your app's launch cycle so it's always present.
How to perform a segue programmatically using performSegue() Swift version: 5.6. Segues are a visual way to connect various components on your storyboard, but sometimes it's important to be able to trigger them programmatically as well as after a user interaction.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With