With SwiftUI’s new lifecycle, you no longer need to explicitly create an AppDelegate. There might still be situations, however, where an AppDelegate is required. This post explains how.
This post is a follow-up to 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 behaved indeterministically— every coder’s nightmare. Sometimes it worked as expected, and sometimes it didn’t. I explained the details in this post on Stackoverflow.
I could only make it work by reintroducing the “good old” AppDelegate.
So, if you need an AppDelegate in your new SwiftUI app, use 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")
}
}
}
}