Search code examples
iosswiftuiviewcontrollerios13xcode11

How to use old method of setting rootViewController in AppDelegate using Swift


I just started a new project of iOS. I created the project using xcode 11 and iOS 13. When I created project i found out that in order to set our own rootController we have to use sceneDelegate instead of AppDelegate. I want to ask if there is any possibility to use old method of setting rootControllers in AppDelegate instead of using sceneDelegate.

 import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {


    var window : UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        let loginController: HomeViewController = HomeViewController(nibName: "HomeViewController", bundle: nil)

       //        let navController: UINavigationController = UINavigationController(rootViewController: loginController)
               self.window?.rootViewController = loginController
               self.window?.makeKeyAndVisible()
        // Override point for customization after application launch.
        return true
    }
}

Solution

  • Follow these steps to use AppDelegate and opt-out for SceneDelegate

    1. Go to Info.plist and remove Application Scene Manifest entry from Info.plist.
    2. Remove SceneDelegate.swift
    3. Add var window: UIWindow? in your AppDelegate.swift file
    4. Delete the UISceneSession Lifecycle code from AppDelegate.swift

      import UIKit
      
      @UIApplicationMain
      class AppDelegate: UIResponder, UIApplicationDelegate {
      
      
      var window : UIWindow?
      
      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
          // Override point for customization after application launch.
           let mainStoryBoard = UIStoryboard(name: "Main", bundle: Bundle.main)
           let loginController = mainStoryBoard.instantiateViewController(withIdentifier: "HomeViewController")
           self.window?.rootViewController = loginController
           self.window?.makeKeyAndVisible()
           return true
      }
      }
      

    Make sure to give "HomeViewController" storyboardID to your view controller.

    This is how your AppDelegate.swift file should look now. You are good to go!