Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the rootViewController in iOS

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?

like image 304
Jim Avatar asked Dec 21 '11 06:12

Jim


People also ask

What is rootViewController in iOS?

The root view controller provides the content view of the window. Assigning a view controller to this property (either programmatically or using Interface Builder) installs the view controller's view as the content view of the window.

How do I get the presenting view controller?

Set the modalPresentationStyle property of the new view controller to the desired presentation style. Set the modalTransitionStyle property of the view controller to the desired animation style. Call the presentViewController:animated:completion: method of the current view controller.

How do I get a top view controller?

In addition, you can check for UINavigationController and ask for its topViewController or even check for UITabBarController and ask for selectedViewController . This will get you the view controller that is currently visible to the user.


1 Answers

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];
like image 186
XJones Avatar answered Oct 25 '22 05:10

XJones