- The
@UIApplicationDelegateAdaptorproperty wrapper helps connect anAppDelegateto a SwiftUI app. This allows you to useUIApplicationDelegatemethods, which help manage the app's lifecycle, in a SwiftUI-based app.
import SwiftUI
// Define an AppDelegate class
class AppDelegate: NSObject, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
print("App has launched successfully!")
return true
}
}
@main
struct MyApp: App {
// Attach AppDelegate using @UIApplicationDelegateAdaptor
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
var body: some View {
Text("Hello, SwiftUI with AppDelegate!")
.padding()
}
}- AppDelegate Class: This is a class that helps manage important app events, like when the app starts or goes into the background.
- @UIApplicationDelegateAdaptor: This connects the AppDelegate to a SwiftUI app so it can handle these events.
- SwiftUI Integration: The app begins with
ContentView, butAppDelegateworks in the background to manage things like app startup and background behaviour.
This is helpful when you need to manage push notifications, background tasks, or external tools that require the app to handle special events.