Finding the rootViewController in iOS

Jim picture Jim · Dec 21, 2011 · Viewed 27.4k times · Source

In ShareKit, the code needs to determine where the rootViewController is so it can show a modal view. For some reason, the code is failing in iOS 5:

    // Try to find the root view controller programmically

    // Find the top window (that is not an alert view or other window)
    UIWindow *topWindow = [[UIApplication sharedApplication] keyWindow];
    if (topWindow.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(topWindow in windows)
        {
            if (topWindow.windowLevel == UIWindowLevelNormal)
                break;
        }
    }

    UIView *rootView = [[topWindow subviews] objectAtIndex:0];  
    id nextResponder = [rootView nextResponder];

    if ([nextResponder isKindOfClass:[UIViewController class]])
        self.rootViewController = nextResponder;

    else
        NSAssert(NO, @"ShareKit: Could not find a root view controller.  You can assign one manually by calling [[SHK currentHelper] setRootViewController:YOURROOTVIEWCONTROLLER].");

This is hitting the assert.

What is wrong with simply using the following code, instead?

rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];

This seems to be working fine. Will it fail under some conditions?

Answer

XJones picture XJones · Dec 21, 2011

I'm not sure if you can rely on window.rootViewController b/c you don't have to set it. You can just add a subview to the window. The following seemed to work fine:

id rootVC = [[[[[UIApplication sharedApplication] keyWindow] subviews] objectAtIndex:0] nextResponder];