当我们在前台收到远程推送,或者需要封装一个兼容iOS9之后的UIAlertController
的弹出警告框等等场景时,我们需要去获取当前屏幕显示的UIViewController,具体方法如下:
//获取当前屏幕显示的UIViewController
- (UIViewController *)getCurrentVC {
UIViewController *result = nil;
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
if (window.windowLevel != UIWindowLevelNormal) {
NSArray *windows = [[UIApplication sharedApplication] windows];
for(UIWindow *tmpWin in windows) {
if (tmpWin.windowLevel == UIWindowLevelNormal) {
window = tmpWin;
break;
}
}
}
UIView *frontView = [[window subviews] objectAtIndex:0];
id nextResponder = [frontView nextResponder];
if ([nextResponder isKindOfClass:[UIViewController class]])
result = nextResponder;
else
result = window.rootViewController;
return result;
}
网友评论