How To Add AppDelegate In SwiftUI

As you may notice there isn’t AppDelegate.swift anymore but you could need to execute some code before the app launches.

First create, AppDelegate.swift file and add the method you need, let’s say application(_:didFinishLaunchingWithOptions:) method. Remember about importing UIKit.

import UIKit

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

    
    return true
    }
}

And this file you can treat as AppDelegate in the UIKit project.

Next, open a file called the same as your project and where you have a struct with @main annotation.

And add this:

@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

The result should look like this. My application is called AppDelegateTestApp.

import SwiftUI

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

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

You don’t need to execute any code on appDelegate instance, it’ll work itself.