Understanding the Application Lifecycle - codepath/ios_guides GitHub Wiki

TODO:

  • Awaking from Push Notifications
  • Awaking from Location Changes

State Changes in an iOS app

An iOS application can transition between the following states:

  1. Not running
  2. Inactive (e.g. there is a phone call)
  3. Active
  4. Background
  5. Suspended

State Changes in an iOS App

The application delegate

App-level lifecycle events — launch and termination of the entire app — flow through the application delegate. On iOS 13 and later, scene-level state changes (and the window / root view controller setup) moved to the scene delegate covered below; the snippet that follows shows the pre-scene pattern for setting up the window in application:didFinishLaunchingWithOptions: without a storyboard:

For example:

    func application(_ application: UIApplication,
            didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        self.window = UIWindow(frame: UIScreen.main.bounds)
        let rootViewController = ViewController()
        self.window?.rootViewController = rootViewController
        self.window?.makeKeyAndVisible()
        
        return true
    }

The scene delegate

The AppDelegate is now only responsible for the application lifecycle and setup, since iOS 13. The SceneDelegate will be responsible for what is shown on the screen (Windows or Scenes) handle and manage the way your app is shown.

So, if you are not using storyboards you will need to set up the window and root view controller of your application in scene:willConnectTo:options:

For example:

  func scene(_ scene: UIScene, 
             willConnectTo session: UISceneSession, 
             options connectionOptions: UIScene.ConnectionOptions) {

        guard let windowScene = (scene as? UIWindowScene) else { return }
        window = UIWindow(windowScene: windowScene)
        
        let rootViewController = ViewController()

        window?.rootViewController = rootViewController
        window?.makeKeyAndVisible()
    }

If you are using a storyboard you simply specify the "main interface" in your project settings. (Remember to also set the initial view controller on the storyboard)