Skip to main content

How to add an AppDelegate to a SwiftUI app

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to add an AppDelegate to a SwiftUI app 관련

SwiftUI by Example

Back to Home

How to add an AppDelegate to a SwiftUI app | SwiftUI by Example

How to add an AppDelegate to a SwiftUI app

Updated for Xcode 15

SwiftUI apps launch using a custom struct that conforms to the App protocol, but sometimes you might want to get back the old UIApplicationDelegate functionality we used to have – perhaps to handle registration for push notifications, to respond to memory warnings, to detect time changes, and so on.

To do this, first create a custom class that inherits from NSObject and conforms to the UIApplicationDelegate protocol, like this:

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

I've added didFinishLaunchingWithOptions in there, but you only need to implement the methods you care about.

And now in your App scene, use the UIApplicationDelegateAdaptor property wrapper to tell SwiftUI it should use your AppDelegate class for the application delegate.

@main
struct NewIn14App: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

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

SwiftUI is responsible for creating that delegate and looking after its lifetime, so you can go ahead and add any other app delegate functionality to that class to have it called.

Tips

For push notifications, you should probably adjust the delegate property of UNUserNotificationCenter.current() so that it points to a custom class you own.

Similar solutions…
How to add in-app purchases in SwiftUI | SwiftUI by Example

How to add in-app purchases in SwiftUI
How to add Metal shaders to SwiftUI views using layer effects | SwiftUI by Example

How to add Metal shaders to SwiftUI views using layer effects
How to create a document-based app using FileDocument and DocumentGroup | SwiftUI by Example

How to create a document-based app using FileDocument and DocumentGroup
How to add Core Data objects from SwiftUI views | SwiftUI by Example

How to add Core Data objects from SwiftUI views
How to detect when your app moves to the background or foreground with scenePhase | SwiftUI by Example

How to detect when your app moves to the background or foreground with scenePhase

이찬희 (MarkiiimarK)
Never Stop Learning.