Using UIApplicationDelegateAdaptor in SwiftUI
tl;dr:A quick introduction to using UIApplicationDelegateAdaptor to connect UIKit's application delegate lifecycle with a SwiftUI app.
SwiftUI provides its own application lifecycle through the App protocol:
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
For most apps, this is enough. However, some UIKit APIs and third-party SDKs still rely on UIApplicationDelegate.
SwiftUI provides @UIApplicationDelegateAdaptor for these cases.
Creating an App Delegate
First, create a traditional UIApplicationDelegate:
import UIKit
final class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
print("Application launched")
return true
}
}
Then attach it to the SwiftUI app:
import SwiftUI
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self)
private var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
SwiftUI creates the AppDelegate and connects it to the underlying UIApplication.
The application still uses the SwiftUI lifecycle, but UIKit delegate callbacks can now be handled by AppDelegate.
When Is It Useful?
One common example is remote notifications. APNs registration results are delivered through UIApplicationDelegate:
final class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
print("Device token:", deviceToken)
}
func application(
_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error
) {
print("Registration failed:", error)
}
}
It can also be useful when integrating frameworks that still expect an application delegate.
SwiftUI and UIKit Together
@UIApplicationDelegateAdaptor does not replace SwiftUI’s App lifecycle with the old UIKit lifecycle.
Instead, it acts as a bridge:
SwiftUI App
│
├── WindowGroup
│
└── @UIApplicationDelegateAdaptor
│
▼
UIApplicationDelegate
This makes it possible to keep a modern SwiftUI application structure while still accessing UIKit lifecycle APIs when necessary.
For macOS applications, SwiftUI provides the equivalent @NSApplicationDelegateAdaptor for integrating NSApplicationDelegate.