Skip to main content

How I Start A SwiftUI Project - Revisited

·2 mins

The AppDelegate Is Back #

There is no need any more to explicitly create an AppDelegate with SwiftUI’s new lifecycle. There might be situations where an AppDelegate might still be required though. This post explains how.

This post is a follow-up on my first post “How I Start A SwiftUI Project”.

While creating an app for my tutorial series “Programming DJI Drones”, I ran into a strange problem.

My app was behaving indeterministic, every coders nightmare. Sometimes it would work as expected, and sometimes not. I have explained all details in this post on Stackoverflow.

I could only make it work to re-introduce the “good old” AppDelegate again.

So, whenever there is a need to use an AppDelegate in your new shiny SwiftUI app, see the blueprint below.

Feel free to buy me a coffee if you liked this post.

import SwiftUI

class AppDelegate: UIResponder, UIApplicationDelegate {

    var someClass = SomeClass()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        someClass.doSomethingThatWouldNotWorkBefore()
        return true
    }
}

@main
struct MyApp: App {

    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    @Environment(\.scenePhase) private var scenePhase

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .onChange(of: scenePhase) { (newScenePhase) in
            switch newScenePhase {
            case .active:
                print("active")
            case .background:
                print("background")
            case .inactive:
                print("inactive")
            @unknown default:
                print("default")
            }
        }
    }
}

Resources #