美文网首页
ios13以后的UIWindow的获取

ios13以后的UIWindow的获取

作者: Johnson_9d92 | 来源:发表于2021-12-12 13:01 被阅读0次

    ios13以后的UIWindow的获取

        @objc public static func getCurrentWindow() -> UIWindow {
            if let window: UIWindow = (UIApplication.shared.delegate?.window)! {
                debugPrint(window)
                return window
            } else {
                if #available(iOS 13.0, *) {
                    let arr: Set = UIApplication.shared.connectedScenes
                    let windowScene: UIWindowScene = arr.first as! UIWindowScene
                //如果是普通APP开发,可以使用
                // SceneDelegate * delegate = (SceneDelegate *)windowScene.delegate;
                   //UIWindow * mainWindow = delegate.window;
                 if let mainWindow: UIWindow = windowScene.value(forKeyPath: "delegate.window") as? UIWindow {
                        return mainWindow
                    } else {
                        return UIApplication.shared.windows.first!
                    }
                }else{
                    return UIApplication.shared.keyWindow!
                }
            }
        }
    
    
    }
    
    

    oc

    +(UIWindow *)getCurrentWindow{
        
        if([[[UIApplication sharedApplication] delegate] window]){
            return [[[UIApplication sharedApplication] delegate] window];
        }else {
            if (@available(iOS 13.0,*)) {
                NSArray *arr = [[[UIApplication sharedApplication] connectedScenes] allObjects];
                UIWindowScene *windowScene =  (UIWindowScene *)arr[0];
                //如果是普通APP开发,可以使用
                //SceneDelegate *delegate = (SceneDelegate *)windowScene.delegate;
                //UIWindow *mainWindow = delegate.window;
                
                //  由于在sdk开发中,引入不了SceneDelegate的头文件,所以需要使用kvc获取宿主的app的window
                UIWindow *mainWindow = [windowScene valueForKeyPath:@"delegate.window"];
                if(mainWindow){
                    return mainWindow;
                }else{
                    return [UIApplication sharedApplication].windows.lastObject;
                }
            }else {
                return [UIApplication sharedApplication].keyWindow;
            }
            
        }
    }
    

    相关文章

      网友评论

          本文标题:ios13以后的UIWindow的获取

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