AppDelegate and SceneDelegate when supporting iOS 12 and 13

后端 未结 3 726
忘掉有多难
忘掉有多难 2020-12-10 05:12

I need to support iOS 12 and iOS 13.

Should I be duplicating code between AppDelegate and SceneDelegate?

For example:



        
3条回答
  •  忘掉有多难
    2020-12-10 06:07

    You do need to duplicate the code but you need to make sure it runs only on the correct system. In iOS 13 you don’t want that application delegate didFinishLaunching body code to run, so use an availability check to prevent it. In the same way, use availability to hide the window scene stuff from iOS 12.

    Here's the basic sketch of a solution that runs correctly on both iOS 12 and iOS 13:

    AppDelegate.Swift

    import UIKit
    @UIApplicationMain
    class AppDelegate : UIResponder, UIApplicationDelegate {
        var window : UIWindow?
        func application(_ application: UIApplication,
            didFinishLaunchingWithOptions 
            launchOptions: [UIApplication.LaunchOptionsKey : Any]?)
            -> Bool {
                if #available(iOS 13, *) {
                    // do only pure app launch stuff, not interface stuff
                } else {
                    self.window = UIWindow()
                    let vc = ViewController()
                    self.window!.rootViewController = vc
                    self.window!.makeKeyAndVisible()
                    self.window!.backgroundColor = .red
                }
                return true
        }
    }
    

    SceneDelegate.swift

    import UIKit
    @available(iOS 13.0, *)
    class SceneDelegate: UIResponder, UIWindowSceneDelegate {
        var window : UIWindow?
        func scene(_ scene: UIScene,
            willConnectTo session: UISceneSession,
            options connectionOptions: UIScene.ConnectionOptions) {
                if let windowScene = scene as? UIWindowScene {
                    self.window = UIWindow(windowScene: windowScene) 
                    let vc = ViewController()                      
                    self.window!.rootViewController = vc             
                    self.window!.makeKeyAndVisible()                 
                    self.window!.backgroundColor = .red
                }
        }
    }
    

    ViewController.swift

    import UIKit
    class ViewController : UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()
            print("view did load")
            self.view.backgroundColor = .green
        }
    }
    

    Note that dealing with other duplicates, such as the application activating, is much simpler because if you support window scenes the application delegate method won't be called on iOS 12. So the problem is confined to this one situation, namely where you have window / root view controller manipulations to perform at launch (e.g. no storyboard).

提交回复
热议问题