Skip to content

Instantly share code, notes, and snippets.

@hunje
Last active September 15, 2015 05:26
Show Gist options
  • Save hunje/798ab595765cc9752ec1 to your computer and use it in GitHub Desktop.
Save hunje/798ab595765cc9752ec1 to your computer and use it in GitHub Desktop.
looking for current Root View Controller through UIApplication.keyWindow.
+ (UIViewController *)getRootViewController {
UIViewController *result = nil;
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]]) {
result = nextResponder;
} else if ([topWindow respondsToSelector:@selector(rootViewController)]
&& topWindow.rootViewController != nil) {
result = topWindow.rootViewController;
} else {
NSAssert(NO, @"Could not find a root view controller.");
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment