Swift Xcode 11 iOS 13 Scene Delegate Life Cycle Example

When you create an iOS 13 project in Xcode 11 use single view app template, you will find Xcode 11 add a SceneDelegate.swift file automatically besides the AppDelegate.swift file. It define a SceneDelegate class in the SceneDelegate.swift file, and this class takes over some UI life cycle functions which is implemented by AppDelegate class before. This article will show you an example about how the SceneDelegate class manage the iOS app UI Life cycle functions.

1. Difference Between AppDelegate & SceneDelegate Class Life Cycle Methods In Xcode 11 iOS 13.

Before iOS version 13, the AppDelegate class manages all the iOS app’s life cycle methods, that includes Process Lifecycle and UI Lifecycle methods like below picture.

ios app delegate class managed life cycle methods before ios version 13

But from iOS version 13, it add SceneDelegate class that is implemented in SceneDelegate.swift file. This class will manage the iOS app’s UI Lifecycle methods, and the original AppDelegate class only manages the iOS app’s Process Lifecycle methods. You can see that in below picture.

ios app delegate class only manage process lifecycle methods in ios version 13

ios scene delegate class manage app ui lifecycle

2. SceneDelegate Class UI LifeCycle Methods.

When you edit the SceneDelegate.swift file, you can see it has already add some functions and property, we will list them below.

  1. var window: UIWindow? : This property is used to refer to the scene UI window, it is implemented in AppDelegate class before. But now it is implemented in SceneDelegate class. One iOS app can has multiple scenes.

  2. func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions: This function is invoked when this scene is initialized and connect to the window. You can create the root view controller object and assign the root view controller object to the SceneDelegate class’s window property in this function ( you can read article How To Set Application Root View Controller Programmatically In Xcode 11 ) . It is originally implemented in AppDelegate class’s func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions [UIApplication.LaunchOptionsKey: Any]?) -> Bool function before iOS version 13.

  3. func sceneWillEnterForeground(_ scene: UIScene) : This function is invoked when the scene transit from background to foreground.

  4. func sceneDidBecomeActive(_ scene: UIScene) : This function is invoked when the scene state is changed from inactive to active. For example, when you choose to display an iOS app window from iOS app switcher ( By double press the iPhone’s home key etc ). This function is called after function sceneWillEnterForeground.

  5. func sceneWillResignActive(_ scene: UIScene) : This function is called when the scene state is changed to inactive from active. For example, if you single press the iPhone’s home key to hide the showing iOS example app to enter background. This function will be invoked before enter background.

  6. func sceneDidEnterBackground(_ scene: UIScene) : This function is called when the iOS app enter background. It is invoked after function sceneWillResignActive in general.
  7. func sceneDidDisconnect(_ scene: UIScene) : This function is called a little while after the iOS app enter iOS background, generally you write some resource release codes in this function.
READ :   iOS Xcode Project And Target Structure Example

3. AppDelegate Class Added Functions.

Besides SceneDelegate class, AppDelegate class also add two functions as below.

  1. func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration : This function is called when it create a session object for this scene.
  2. func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) : This function is called when user discard a scene session.

4. Application Scene Manifest.

Besides SceneDelegate.swift file, the Xcode 11 single view app template also add some scene manifest configuration data in the project Info.plist file.

You can click the Info.plist file in Xcode left project navigator panel, then you can find Application Scene Manifest item in center editor panel. When you expand the Application Scene Manifest item, it will list all the scenes configuration data. You can edit the scene’s Configuration Name, Delegate Class Name, Storyboard Name item’s value at there.

xcode scene configuration data in info plist file

5. iOS 13 Xcode 11 Scene Delegate Example Source Code.

  1. Create iOS sing view app project in Xcode 11.
  2. Write below source code in AppDelegate.swift file.
    //
    //  AppDelegate.swift
    //  iOSAppUseXibFiles
    //
    //  Created by song zhao on 10/26/19.
    //  Copyright © 2019 dev2qa.com. All rights reserved.
    //
    
    import UIKit
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
        
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
            return true
        }
    
        // MARK: UISceneSession Lifecycle
    
        func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
            // Called when a new scene session is being created.
            // Use this method to select a configuration to create the new scene with.
            
            print("application ---> connectingSceneSession")
            
            return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
        }
    
        func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
            // Called when the user discards a scene session.
            // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
            // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
            
            print("application ---> didDiscardSceneSessions")
            
        }
    
    
    }
    
    
  3. Write below source code in SceneDelegate.swift file.
    //
    //  SceneDelegate.swift
    //  iOSAppUseXibFiles
    //
    //  Created by song zhao on 10/26/19.
    //  Copyright © 2019 dev2qa.com. All rights reserved.
    //
    
    import UIKit
    
    class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
        var window: UIWindow?
    
        func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
            
            print("scene ---> willConnectTo.")
            guard let _ = (scene as? UIWindowScene) else { return }
        }
    
        func sceneDidDisconnect(_ scene: UIScene) {
            // Called as the scene is being released by the system.
            // This occurs shortly after the scene enters the background, or when its session is discarded.
            // Release any resources associated with this scene that can be re-created the next time the scene connects.
            // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
            
            print("scene ---> sceneDidDisconnect.")
        }
    
        func sceneDidBecomeActive(_ scene: UIScene) {
            // Called when the scene has moved from an inactive state to an active state.
            // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
            print("scene ---> sceneDidBecomeActive.")
        }
    
        func sceneWillResignActive(_ scene: UIScene) {
            // Called when the scene will move from an active state to an inactive state.
            // This may occur due to temporary interruptions (ex. an incoming phone call).
            print("scene ---> sceneWillResignActive.")
        }
    
        func sceneWillEnterForeground(_ scene: UIScene) {
            // Called as the scene transitions from the background to the foreground.
            // Use this method to undo the changes made on entering the background.
            print("scene ---> sceneWillEnterForeground.")
        }
    
        func sceneDidEnterBackground(_ scene: UIScene) {
            // Called as the scene transitions from the foreground to the background.
            // Use this method to save data, release shared resources, and store enough scene-specific state information
            // to restore the scene back to its current state.
            print("scene ---> sceneDidEnterBackground.")
        }
    
    
    }
    
    
  4. When you run this example, you will see the debug output text in the debug active console by click Xcode menu View —> Debug Area —> Show Debug Area.
    application ---> connectingSceneSession
    
    scene ---> willConnectTo.
    
    scene ---> sceneWillEnterForeground.
    
    scene ---> sceneDidBecomeActive.
    
    scene ---> sceneWillResignActive.
    
    scene ---> sceneDidEnterBackground.
    
    scene ---> sceneDidDisconnect.
    
    application ---> didDiscardSceneSessions
    

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.