LifeCycle methods

Hello SwiftUI Team,

Just watched the "App essentials..." session and came to think about application life cycle methods. In UIKit we are able to hook into the app launch life cycle via the UIApplicationDelegate but am I getting it right that it isn't supported out of the box when using pure SwiftUI and the App protocol (as you need to support multiple platforms with different launch characteristics)?

It seems like the only feature I'm able to access from UIApplicationDelegate is the openURL (via the @Environment property wrapper).

Last but not least. Do you have a recommended way of obtaining the same life cycle methods provided by UIApplicationDelegate from SwiftUI? Or is it simply to early to adopt the usage of the App protocol if you rely on some of the more "exotic" delegate methods from UIApplicationDelegate?

Regards,

Jens
Answered by mtsrodrigues in 615618022
You can manage the App life cycle using @Environment(\.scenePhase) and @UIApplicationDelegateAdaptor as following:

Code Block swift
class AppDelegate: NSObject, UIApplicationDelegate {
    func applicationDidFinishLaunching(_ application: UIApplication) {
        print(#function)
    }
}
@main
struct SampleApp: App {
    @Environment(\.scenePhase) private var scenePhase
    @UIApplicationDelegateAdaptor private var appDelegate: AppDelegate
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .onChange(of: scenePhase) { phase in
            switch phase {
            case .active:
                print("active")
            case .inactive:
                print("inactive")
            case .background:
                print("background")
            }
        }
    }
}

Accepted Answer
You can manage the App life cycle using @Environment(\.scenePhase) and @UIApplicationDelegateAdaptor as following:

Code Block swift
class AppDelegate: NSObject, UIApplicationDelegate {
    func applicationDidFinishLaunching(_ application: UIApplication) {
        print(#function)
    }
}
@main
struct SampleApp: App {
    @Environment(\.scenePhase) private var scenePhase
    @UIApplicationDelegateAdaptor private var appDelegate: AppDelegate
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .onChange(of: scenePhase) { phase in
            switch phase {
            case .active:
                print("active")
            case .inactive:
                print("inactive")
            case .background:
                print("background")
            }
        }
    }
}

Cool, thanks! I didn't notice the @UIApplicationDelegateAdaptor property wrapper. Thanks for the feedback
LifeCycle methods
 
 
Q