How/where do SwiftUI “App” objects handle AppleEvents

I was looking through:

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ScriptableCocoaApplications/SApps_handle_AEs/SAppsHandleAEs.html

And wondered how these are handled for SwiftUI apps. What would I add or override?

Answered by DTS Engineer in 917783022

Yes. As the earlier reply says, NSApplicationDelegateAdaptor is where to start. It gives your SwiftUI app an NSApplicationDelegate. The delegate methods I tested work as they do in an AppKit app, apart from opening files in a DocumentGroup app.

I tested this in macOS 27.0.1. I built one delegate into a SwiftUI app that uses WindowGroup, a SwiftUI app that uses DocumentGroup, and an AppKit app that isn't document-based. I sent each app the open documents, print documents, and reopen events, and a URL with a custom scheme. All three called application(_:printFiles:withSettings:showPrintPanels:) for print, applicationShouldHandleReopen(_:hasVisibleWindows:) for reopen, and application(_:open:) for the URL.

For a file, the WindowGroup and AppKit apps called application(_:open:). The DocumentGroup app opened the file as a document instead, and didn't call the delegate.

For other Apple events, register your own handler with NSAppleEventManager. The NSApplication documentation says applicationWillFinishLaunching(_:) "is generally the best place to do so." A handler registered there received a custom event in all three apps.

NSApplicationDelegateAdaptor would be your starting point.

Yes. As the earlier reply says, NSApplicationDelegateAdaptor is where to start. It gives your SwiftUI app an NSApplicationDelegate. The delegate methods I tested work as they do in an AppKit app, apart from opening files in a DocumentGroup app.

I tested this in macOS 27.0.1. I built one delegate into a SwiftUI app that uses WindowGroup, a SwiftUI app that uses DocumentGroup, and an AppKit app that isn't document-based. I sent each app the open documents, print documents, and reopen events, and a URL with a custom scheme. All three called application(_:printFiles:withSettings:showPrintPanels:) for print, applicationShouldHandleReopen(_:hasVisibleWindows:) for reopen, and application(_:open:) for the URL.

For a file, the WindowGroup and AppKit apps called application(_:open:). The DocumentGroup app opened the file as a document instead, and didn't call the delegate.

For other Apple events, register your own handler with NSAppleEventManager. The NSApplication documentation says applicationWillFinishLaunching(_:) "is generally the best place to do so." A handler registered there received a custom event in all three apps.