G. Marc
G. Marc

Reputation: 6037

SwiftUI: AppDelegate on MacOS

I'm porting a SwiftUI iOS app to macOS. It uses the @UIApplicationDelegateAdaptor property wrapper to bind a UIApplicationDelegate class. Unfortunately, the UIApplicationDelegate class isn't available on macOS, so I'm wondering how I bind my custom AppDelegate.

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

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

    var body: some Scene {
        ...
    }
}

Upvotes: 13

Views: 6867

Answers (2)

MacUserT
MacUserT

Reputation: 1953

it's almost the same, but then use NS instead of UI. I did it slightly different than you:

@main
struct MyApp: App {
    
    // MARK: - Properties
    // Used variables
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    @Environment(\.openURL) var openURL
    
    var body: some Scene {
        WindowGroup {
            MainControlView()
        }
        .commands {
            FileMenuCommands(listOfContainers: listOfContainers)
        }
    }
}

Then you can write your application delegate like:

import AppKit
import SwiftUI

class AppDelegate: NSObject, NSApplicationDelegate {
    // Whatever you want to write here
}

This all worked for me.

Upvotes: 10

vadian
vadian

Reputation: 285250

The macOS equivalent has the NS prefix

import AppKit

class AppDelegate: NSObject, NSApplicationDelegate {

...

@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

and the DidFinishLaunching delegate method has a different signature

func applicationDidFinishLaunching(_ aNotification: Notification) [ ...

Upvotes: 14

Related Questions