Streetboy Streetboy - 1 year ago 1315
Swift Question

How to get root view controller?

I need an instance of root view controller. However this code return null:

UIViewController *rootViewController = (UIViewController*)[[[UIApplication sharedApplication] keyWindow] rootViewController];

Any ideas why ?

Also when i try to get array of controllers:

NSArray *viewControllers = self.navigationController.viewControllers;

This return just one controller, but this return isn't my root view controller.

If i try to call this:

UIViewController *root = (UIViewController*)[self.navigationController.viewControllers objectAtIndex:0];

This still returning null.

What else i could try to get instance of my root view controller ?


Answer Source

if you are trying to access the rootViewController you set in your appDelegate. try this:


YourViewController *rootController =(YourViewController*)[[(YourAppDelegate*)
                                   [[UIApplication sharedApplication]delegate] window] rootViewController];


let appDelegate  = UIApplication.sharedApplication().delegate as AppDelegate
let viewController = appDelegate.window!.rootViewController as YourViewController
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download