在iOS 13中获取根视图控制器的正确方法是什么?

class TopViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //Code Block 1
        let controller = getTopController()
        print(controller)// Prints out MyTestProject.TopViewController

        //Code Block 2
        let controller2 = getRootController()
        print(controller2)//Prints out nil , because keywindow is also nil upto this point.

        //Code Block 3
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            let controller2 = self.getRootController()
            print(controller2)// Prints out MyTestProject.TopViewController   
        }
    }

    func getTopController() -> UIViewController? {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
            let sceneDelegate = windowScene.delegate as? SceneDelegate else {
                return nil
        }
        return sceneDelegate.window?.rootViewController
    }

    func getRootController() -> UIViewController? {
        let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
        let topController = keyWindow?.rootViewController
        return topController
    }
}

从iOS 13开始,有两种方法可获取应用程序的当前活动/顶视图控制器。 这里: getTopController()和getRootController()展示了这两种方法。

正如print()之外的代码中注释的那样,结果却有所不同。

在代码块2中: getRootController找不到窗口,因此它显示为nil。为什么会这样呢?

另外,这是在iOS 13中引用顶级控制器的完整证明方法,我现在很困惑?

评论
  • 上集回顾
    上集回顾 回复

    self.view.window will be available in IOS 13 to access Window and root controller