Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform Segue from App Delegate swift

Tags:

ios

swift

segue

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?

like image 316
user3405152 Avatar asked Nov 25 '14 20:11

user3405152


People also ask

What is app delegate and methods in Swift?

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.

What is perform segue?

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.


1 Answers

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)
like image 134
Lyndsey Scott Avatar answered Oct 05 '22 11:10

Lyndsey Scott