场景需求:
1:app在后台挂起状态下收到个远程推送,要进行页面跳转。
2:类似微信,来个视频电话,在收到来电监听后要在任意页面能吊起通话界面 进行跳转
上代码:
+(UIViewController*)getCurrentVC {
UIWindow * window = [[UIApplication sharedApplication] keyWindow];
/*
keyWindow和appdelegate.window可能不是同一个 所以还是查keyWindow
//app默认windowLevel是UIWindowLevelNormal,如果不是,找到UIWindowLevelNormal的
if (window.windowLevel != UIWindowLevelNormal)
{
NSArray *windows = [[UIApplication sharedApplication] windows];
for(UIWindow * tmpWin in windows)
{
if (tmpWin.windowLevel == UIWindowLevelNormal)
{
window = tmpWin;
break;
}
}
}
*/
UIViewController* viewController = window.rootViewController;
return [self findBestViewController:viewController];
}
//循环查找模态和视图容器 如果有自定义容器(自定义TabBarController这种)也要进行相关判断
+ (UIViewController *)findBestViewController:(UIViewController*)vc {
if (vc.presentedViewController) {
return [self findBestViewController:vc.presentedViewController];
} else if ([vc isKindOfClass:[UISplitViewController class]]) {
UISplitViewController* svc = (UISplitViewController*) vc;
if (svc.viewControllers.count > 0)
return [self findBestViewController:svc.viewControllers.lastObject];
else
return vc;
} else if ([vc isKindOfClass:[UINavigationController class]]) {
UINavigationController* navc = (UINavigationController*) vc;
if (navc.viewControllers.count > 0)
return [self findBestViewController:navc.visibleViewController];
else
return vc;
} else if ([vc isKindOfClass:[UITabBarController class]]) {
UITabBarController* tabVC = (UITabBarController*) vc;
if (tabVC.viewControllers.count > 0)
return [self findBestViewController:tabVC.selectedViewController];
else
return vc;
} else {
return vc;
}
}