From Xcode 12 and higher when creating a new project either an App or Document App, the Life Cycle option now contains two options.
SwiftUI App and UIKit App Delegate.
So what is this new SwiftUI App Life Cycle?
With a SwiftUI App it now conforms to a new App protocol, this protocol replaces the AppDelegate class which we use in UIKit and is the main entry point of the app.
When a new project is created it now just creates two swift files. <project name>App.swift and the ContentView.swift
Opening the demoApp.swift file in my sample we can see how simple, clean and concise it is. We have the SwiftUI framework imported, the struct conforms to the App protocol and annotated with @main – indicating this is the entry point of the app. The body property using the some keyword for opaque type is a Scene. (Same technique for ContentView.swift where body property with some opaque type is a View). Then we use the WindowGroup as a container for a view hierarchy presented by the app.
How do we load options now?
The counterpart of AppDelegate’s didFinishLaunchWithOptions is simply calling init() and load your third party libraries and set the options.
How do we manage Scene lifecycles events now?
On SwiftUI App the counterpart is by reading Environment settings for scenePhase – an indication of a scene’s operational state.
Scene phases or state are the following:
- active – the scene is in the foreground and interactive.
- inactive – the scene is in the foreground but should pause its work.
- background – the scene isn’t currently visible in the UI.
We can then call the modifier onChange(of:perform) closure and check the current phase and add our logic.
With the SwiftUI App life cycle it is so concise and clean. It is overly simplified unlike AppDelegate.