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

时间:2019-11-13 18:10:33

标签: ios ios13

    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可以在我的IOS 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类的外观

2 个答案:

答案 0 :(得分:0)

这是在Scene Delegate类中设置App的initialView Controller / rootViewController的方式(该类处理由AppDelegate先前处理的应用程序生命周期方法)。

导入UIKit 导入SwiftUI

SceneDelegate类: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")
}

}

答案 1 :(得分:0)

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

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

如果要使用appDelegate,可以像这样

进行访问
let AppDelegate = UIApplication.shared.delegate as! AppDelegate

这同时适用于IOS12和IOS13,因此,您无需更改代码