美文网首页
获取app当前展示的ViewController

获取app当前展示的ViewController

作者: 惊蛰_e3ce | 来源:发表于2019-11-21 21:14 被阅读0次

    场景需求:
    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;
        }
    }
    

    相关文章

      网友评论

          本文标题:获取app当前展示的ViewController

          本文链接:https://www.haomeiwen.com/subject/zjkxwctx.html