Home > OS >  SwiftUI: AppDelegate on MacOS
SwiftUI: AppDelegate on MacOS

Time:02-28

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 {
        ...
    }
}

CodePudding user response:

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) [ ...

CodePudding user response:

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.

Kind regards, MacUserT

  • Related