我正在尝试使用 didFinishLoadingWithOptions 方法从 AppDelegate 获取 rootViewController,但我无法访问 window

I am trying to get the rootViewController from the AppDelegate using the didFinishLoadingWithOptions method, but I can't access the window

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    if let navController = window.rootViewController as? UINavigationController,
        let personController = navController.controllers[0] as? PeopleTableViewController{
        print("something")
    }
    return true
}

但它给了我一个错误,它没有识别 AppDelegate 的 window 属性,他们是否更改为 IOS 13 因为它在我的 [=19] 中有效=] 12 个项目

class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
lazy var persistentContainer: NSPersistentContainer = {
     let container = NSPersistentContainer(name: "DataModel")
     container.loadPersistentStores { description, error in
         if let error = error {
             fatalError("Unable to load persistent stores: \(error)")
         }
     }
     return container
 }()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    if let navController = window?.rootViewController as? UINavigationController,
        let personController = navController.viewControllers[0] as? PeopleTableViewController{
        personController.persistentContainer = persistentContainer
        print("Nailed it ")
    } else {
        print("Sorry")
    }
    return true
}

// MARK: UISceneSession Lifecycle

func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}

func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}

func applicationWillTerminate(_ application: UIApplication) {
    persistentContainer.saveContextIfNeeded()
}

}

这就是我的 AppDelegate class 的样子

这是在场景委托 class 中设置 App 的 initialView Controller/rootViewController 的方法(这个 class 处理 AppDelegate 之前处理的应用程序生命周期方法)。

导入 UIKit 导入 SwiftUI

class场景委托:UIResponder,UIWindowSceneDelegate {

var window: UIWindow?


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


    let initialViewController = UIStoryboard(name: "Storyboard", bundle: nil).instantiateViewController(identifier: "DatePicker")  as! DatePicker

    let navigation = UINavigationController(rootViewController: initialViewController)

    // Use a UIHostingController as window root view controller.
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = tabBarCnt
        self.window = window
        window.makeKeyAndVisible()
    }
}

func sceneDidDisconnect(_ scene: UIScene) {
    // Called as the scene is being released by the system.
    // This occurs shortly after the scene enters the background, or when its session is discarded.
    // Release any resources associated with this scene that can be re-created the next time the scene connects.
    // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
}

func sceneDidBecomeActive(_ scene: UIScene) {
    // Called when the scene has moved from an inactive state to an active state.
    // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}

func sceneWillResignActive(_ scene: UIScene) {
    // Called when the scene will move from an active state to an inactive state.
    // This may occur due to temporary interruptions (ex. an incoming phone call).
}

func sceneWillEnterForeground(_ scene: UIScene) {
    // Called as the scene transitions from the background to the foreground.
    // Use this method to undo the changes made on entering the background.
}

func sceneDidEnterBackground(_ scene: UIScene) {
    // Called as the scene transitions from the foreground to the background.
    // Use this method to save data, release shared resources, and store enough scene-specific state information
    // to restore the scene back to its current state.

    print("App entered Background")
}

}

我找到了解决方法。而不是将代码放在 didFinsishLoadingWithOptions 方法中,而是获取 UIview comptroller 的 persistentContainer 变量,然后在 AppDelegate 中传递 persistentContainer。您可以将其添加到视图控制器的顶部。

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.context

如果你想要 appDelegate,你可以像这样访问

let AppDelegate = UIApplication.shared.delegate as! AppDelegate

这对 IOS12 和 IOS13 都有效,因此您不必更改代码