Accessing the Root View Controller at Launch on iOS 13 with SceneDelegate

A new SceneDelegate was introduced for Storyboard-based apps in iOS 13, and with it came some changes in how you’re able to access your app’s root view controller at app launch.

The Old Way

AppDelegate Swift file used to be where code landed for accessing your app’s rootViewController:

1    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
2        // Override point for customization after application launch.
3        let rootVC = window?.rootViewController
5        return true
6    }

What To Do Now

Now, you’ll be moving that code over to your app’s SceneDelegate Swift file:

 1class SceneDelegate: UIResponder, UIWindowSceneDelegate {
 3    var window: UIWindow?
 6    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
 7        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
 8        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
 9        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
10        guard let _ = (scene as? UIWindowScene) else { return }
12        let rootVC = self.window?.rootViewController 
13    }
15    // ... the rest of SceneDelegate
comments powered by Disqus