从 iOS 11+ 项目中删除 SceneDelegate 的正确方法 - 应用程序中需要什么代码(_:didFinishLaunchingWithOptions)

Correct way of removing SceneDelegate from iOS 11+ project - What code is necessary in application(_: didFinishLaunchingWithOptions)

在 Xcode 12 中创建新的 iOS 项目时,会自动添加一个 UISceneDelegate。由于我的应用程序应该在 iOS 11+(不支持 UISceneDelegate)上可用,所以我不得不将其删除。

info.plistAppDelegate 中删除 UISceneDelegate 当然没有问题。但是我想知道我是否必须向 application(_: didFinishLaunchingWithOptions) 添加任何代码在大多数教程中我发现此方法只是留空,只需要添加 var window: UIWindow?。其他来源显示必须添加一些设置代码。

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
        /* Manual Setup */
        // let window = UIWindow(frame: UIScreen.main.bounds)    
        // window.rootViewController = ViewController() // Your initial view controller.
        // window.makeKeyAndVisible()
        // self.window = window

        return true
    }
} 

在我的测试中,一切正常,无需任何额外的设置代码。 rootViewController 是从 Storyboard 自动加载的,一切正常。

这只是巧合吗,这是后台发生的一些 Xcode 魔术(如果代码丢失会自动添加 rootVC),还是我的代码(没有设置)损坏并最终会在某些非常糟糕的情况下失败时刻

你只需要确定

1-UISceneDelegate被删除

2- 键 UIApplicationSceneManifest 已从 Info.plist

中删除

3- 这些方法已从 AppDelegate

中删除
// 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.
}

4- 将 var window: UIWindow? 添加到 AppDelegate

5- 确保在 Main.storyboard

中选择了入口点 vc

之后什么都不用担心,将 didFinishLaunchingWithOptions 留空,就好像 Xcode 11

中没有发生任何变化一样