Navigate From AppDelegate.swift to a Different ViewController

With this short code example I am going to share with you how to navigate to a different ViewController from AppDelegate.swift file. The steps are as follows:

  • Create an instance of UIStoryboard,
    let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)

    Note the name of the storyboard I am using. The “Main” is the default name of your storyboard when you create a project. If you rename your storyboard to a different name, you will have to use a different name then in the line above.

  • Instantiate View Controller with Identifier,
    let homePage = mainStoryboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController

    The “HomeViewController” identifier I am using in the code line above is the identifier of the ViewController I have created on my Storyboard. Use the identifier if your ViewController you want to navigate to.

  • Set the Root View Controller of your app’s window to a different one
    self.window?.rootViewController = homePage

    Now I am setting the rootViewController of my app’s window object to a view controller I need to navigate.

    Below is a complete code example of how to go take user from AppDelegate to a different ViewController.

From AppDelegate.swift to a Different ViewController

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
     // Override point for customization after application launch.
 
    
      // Take user to a home page
         let mainStoryboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
         let homePage = mainStoryboard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
         self.window?.rootViewController = homePage
    
   
     return true
 }

I hope this Swift code example is helpful for you. Checkout the below video courses to learn more about Mobile App Development for iOS platform with Swift.


Learn iOS Development with these Video Courses

The Complete iOS 11 & Swift Developer Course - Build 20 Apps

Use Xcode 9 & Swift 4 to make real apps like Uber and Instagram, with CoreML & ARKit. Includes AWS Credit and much more. Preview this video course. icon

How to Make a Freaking iPhone App - iOS 11 and Swift 4

iPhone App Development from scratch. Learn how to make iOS apps using Xcode 9. The Basics Include Pokemon Go & Snapchat. Learn to build iOS Apps with Xcode 9 and Swift 4. How to Make a Freaking iPhone App - iOS 11 and Swift 4 icon

iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course

A Complete iOS 11 and Xcode 9 Course with Swift 4 & Objective-C. Preview this video course. iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course icon