谁的视图仅在首次启动时不在 window 层次结构中

Whose view is not in the window hierarchy only in First Launch

我有一个引导屏幕,在新用户首次打开应用程序时向他们展示。 在我的 appDelegate 中,我检查是否是第一次启动。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        window = UIWindow(frame: UIScreen.main.bounds)

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        var initialViewController = storyboard.instantiateViewController(withIdentifier: "OnBoarding")


        let userDefaults = UserDefaults.standard

        if userDefaults.bool(forKey: "onBoardingComplete") {
            initialViewController = storyboard.instantiateViewController(withIdentifier: "MainApp")

        }
        window?.rootViewController = initialViewController
        window?.makeKeyAndVisible()
    }

我还有一个 collectionViewCell,我有一些按钮,当我单击它们时,我会收到一个包含信息的警报。

一键示例

@IBAction func guide3Btn(_ sender: Any) {
        let infoVC = infoService.info(title: "Title", body: "Information")

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

    }

当用户第一次启动应用程序时,如果他点击信息按钮,会得到这个:

Warning: Attempt to present <MyApp.InfoViewController:      0x7f91db45cfb0> on <MyApp.OnbBoardViewController: 0x7f91db506af0> whose view is not in the window hierarchy!

如果用户重新打开应用程序,一切正常。我知道当我们第一次启动时,我们将 onBoarding 作为根控制器,但我不明白如何解决这个问题。

更新

这是信息服务 class。我使用新的情节提要来创建警报。

class InfoService {

    func info(title: String, body: String) -> InfoViewController {
        let storyboard = UIStoryboard(name: "InfoStoryboard", bundle: .main)

        let infoVC = storyboard.instantiateViewController(withIdentifier: "InfoVC") as! InfoViewController

        infoVC.infoBody = body
        infoVC.infoTitle = title

        return infoVC
    }
}

您可以尝试使用 DispatchQueue.main.async 将故事板实例化代码块添加到主线程,如下所示:

我几乎解决了所有 whose view is not in the window hierarchy! 问题。

DispatchQueue.main.async {
    let infoVC = storyboard.instantiateViewController(withIdentifier: "InfoVC") as! InfoViewController

    infoVC.infoBody = body
    infoVC.infoTitle = title
}
    return infoVC

引用自: