IOS 13 UIWindow 实例在应用程序启动期间为 nil

IOS 13 UIWindow instance is nil during application launching

我正在尝试将我的 managedObjectContext 传递给下一个控制器。 我在我的 appDelegate 文件中创建了一个 UIWindow 实例,因为我需要获取我的备用控制器。 但是,Xcode 说我的 UIWindow 实例为零。

这个 id 我的代码:

lazy var managedObjectContext: NSManagedObjectContext = persistentContainer.viewContext

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    let tabController = window!.rootViewController as! UITabBarController
    if let tabViewControllers = tabController.viewControllers {
        let navController = tabViewControllers[0]  as! UINavigationController
        let controller = navController.viewControllers.first as! CurrentLocationViewController
        controller.managedObjectContext = managedObjectContext
    }

    return true
}

有点奇怪。如何解决这个问题?提前致谢。

IOS 13 window is inside SceneDelegate while prior to 13 is inside AppDelegate

将代码移入 SceneDelegate

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    let tabController = window!.rootViewController as! UITabBarController
    if let tabViewControllers = tabController.viewControllers {
       let navController = tabViewControllers[0]  as! UINavigationController
       let controller = navController.viewControllers.first as! CurrentLocationViewController
       controller.managedObjectContext = managedObjectContext
     }
}

另一种可能的解决方案

  1. 在您的 AppDelegate.swift 中声明 var window: UIWindow?
  2. 从您的文件中删除 SceneDelegate.swift
  3. Info.plist 中删除 Application Scene Manifest
  4. 根据需要在 AppDelegate.swift 中使用 window 对象。