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



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