在应用程序委托中添加的视图控制器未显示

时间:2017-05-23 10:06:25

标签: ios swift uikit presentviewcontroller

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    let auth: UIViewController =
        storyBoard.instantiateViewController(withIdentifier: "Auth") as UIViewController

    window?.rootViewController?.present(auth, animated: true, completion: nil)

    return true
}

我收到了错误......

  

警告:尝试出席   在谁的观点不在   窗口层次结构!

我认为在应用程序生命周期中此时尚未正确配置根控制器。

我该怎么做?我想避免让根控制器检查是否需要显示登录屏幕。

2 个答案:

答案 0 :(得分:1)

你可以这样做:

func application(_ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if Settings.appSettings.authToken != nil {
        self.showMainController()
    }
    NotificationCenter.default.addObserver(forName: .authorizationOperationDidSuccess,
        object: nil, queue: nil) { (notification) in
        self.showMainController()
    }

    return true
}

private func showMainController() {
    let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    let controller: UIViewController =
        storyBoard.instantiateViewController(withIdentifier: "Main") as UIViewController
    if self.window == nil {
        self.window = UIWindow(frame: UIScreen.main.bounds)
    }
    self.window?.backgroundColor = UIColor.white
    self.window?.rootViewController = controller
    self.window?.makeKeyAndVisible()
}

private func showAuthorizationController() {
        let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    let controller: UIViewController =
        storyBoard.instantiateViewController(withIdentifier: "Auth") as UIViewController
    if self.window == nil {
        self.window = UIWindow(frame: UIScreen.main.bounds)
    }
    self.window?.backgroundColor = UIColor.white
    self.window?.rootViewController = controller
    self.window?.makeKeyAndVisible()
}

成功登录后

NotificationCenter.default.post(name: .authorizationOperationDidSuccess,
                    object: nil)

答案 1 :(得分:0)

在此处进行更改,

let auth: AuthVC =  storyBoard.instantiateViewController(withIdentifier: "Auth") as AuthVC

// AuthVC is your_VC_name

仍然面临问题,你可以问。