Add AppDelegate to SwiftUI app

When we create a new SwiftUI project in Xcode then it doesn't include the AppDelegate which we might need for different functionality like push notifications. The new SwiftUI main app file looks like this -

import SwiftUI

@main
struct SampleApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

In order to add AppDelegate to this SwiftUI app, first we need to create AppDelegate class like this -

class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        return true
    }
}

Here we have AppDelegate class with didFinishLaunchingWithOptions function. You can add more functions based on your requirements. As for push notifications, we need to add didRegisterForRemoteNotificationsWithDeviceToken.

Now to link this AppDelegate with SwiftUI App, we need to use the UIApplicationDelegateAdaptor property wrapper inside the App declaration to tell SwiftUI about the delegate type

import SwiftUI

@main
struct SampleApp: App {
	@UIApplicationDelegateAdaptor private var appDelegate: AppDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

That's it. Now SwiftUI will handle everything (creating the delegate instance etc.)


You've successfully subscribed to Developer Insider
Great! Next, complete checkout for full access to Developer Insider
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.