SwiftUI AppDelegate: The Entry Point

AppDelegate is the entry point of an iOS or macOS application. When working on a SwiftUI project you don’t have an AppDelegate class but you can add it if you need to. Since AppDelegate is the entry point it’s a great place to handle some critical application work like registering for push notifications.

In the blog post, we will cover how to implement an AppDelegate inside a SwiftUI project, we will also cover how you use the AppDelegate.

What is AppDelegate?

In Swift-based iOS development, AppDelegate is a crucial class that serves as the entry point for your application. It conforms to the UIApplicationDelegate protocol and is responsible for managing the application’s lifecycle, handling system events, and coordinating various aspects of your app’s behavior.

How do I add an app delegate in SwiftUI?

Let’s get to coding — to create an AppDelegate we first need to create a new Swift class, import UIKit, and inherit from NSObject and UIApplicationDelegate.

In the following example, we will create an AppDelegate class and implement the didFinishLaunchingWithOptionsfunction — didFinishLaunchingWithOptionsfunction is the first function to execute when the application comes to the foreground.

import Foundation
import UIKit

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

}

How to use AppDelegate in SwiftUI

We have created our AppDelegate, now it’s time to use it inside the application.

Every SwiftUI application has an App scene struct with a WindowGroup, this is the entry point of a SwiftUI application. In this struct implement the AppDelegate by using UIApplicationDelegateAdaptor:

import SwiftUI

@main
struct FormsApp: App {
    var body: some Scene {
        @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
        
        WindowGroup {
            SomeView()
        }
    }
}

Wrap up AppDelegate

In this blog post, we covered how you can easily implement an AppDelegate in a SwiftUI project. If you use the didFinishLaunchingWithOptionsfunction remember to return true otherwise your application won’t launch.

I hope you can use this in your application — happy coding 🙂

Scroll to Top