objective-cswiftios5uiviewcontrolleruinavigationcontroller

How to get root view controller?


I need an instance of root view controller.

I tried those approaches:

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

Returns: null:

Also when I try to get an array of controllers:

NSArray *viewControllers = self.navigationController.viewControllers;

It returns only one controller, but it isn't my root view controller.

If I try to take from navigation controller:

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

Returns: null:

Any ideas why? What else could I try to get an instance of my root view controller?

Thanks.


Solution

  • 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
    

    Swift 3

    let appDelegate  = UIApplication.shared.delegate as! AppDelegate
    let viewController = appDelegate.window!.rootViewController as! YourViewController
    

    Swift 4 & 4.2

    let viewController = UIApplication.shared.keyWindow?.rootViewController as? YourViewController
    

    Swift 5 & 5.1 & 5.2

    let viewController = UIApplication.shared.windows.first?.rootViewController as? YourViewController