Streetboy Streetboy - 7 months ago 526
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 ?

Thanks.

Answer

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

Objective-C

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

Swift

let appDelegate  = UIApplication.sharedApplication().delegate as AppDelegate
let viewController = appDelegate.window!.rootViewController as YourViewController