ios - 在应用程序委托(delegate)中添加的 View Controller 未出现

标签 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
}

我收到错误...

Warning: Attempt to present on whose view is not in the window hierarchy!

我推测根 Controller 在应用生命周期的此时还没有正确配置。

我该怎么做?我想避免让根 Controller 必须检查它是否需要显示登录屏幕。

最佳答案

你可以这样做:

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)

关于ios - 在应用程序委托(delegate)中添加的 View Controller 未出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44131749/

相关文章:

ios - View Controller 顶部的黑色空间

iphone - 如何以编程方式调用电话?

ios - 向VStack添加左边框

iphone - UIView nextResponder 如何知道 UIViewController 是什么?

ios - textFieldDidChangeSelection : Modifying state during view update, 这将导致未定义的行为

ios - IBOutletCollection - 如何对数组应用排序?

ios - AVPlayer 无法在 iOS 9 上播放

ios - 如何将按钮方面的框架获取到 View ?

快速获取tableview单元格的所有值

ios - 如何在 YouTube Search API v3 中获取内容详细信息? ( swift )