Reputation: 201
I'm building a MacOS app with SwiftUI and it's working pretty nicely in general. But I'm trying to implement a file import feature that is running into an issue I don't understand. I have created a simple custom JSON-based file format that I can export to, and also import without any problems using File menu commands. But I am also trying to allow importing a file by dropping it on the app's icon in the Finder, and that is turning out to be problematic.
The app is designed with a single-window interface, with each file that can be imported/opened being represented as a listing in the main window/view's List interface. When I use the menu command for this it works as expected. When I drop a file on the app icon, it adds the listing represented by the file, but also opens a new instance of the app's main window.
My app is set up with a SwiftUI App struct. Its body consists of a WindowGroup that contains a NavigationStack which in turn contains the main view/window. The App struct also declares a NSApplicationDelegateAdaptor which references an AppDelegate class. That AppDelegate class includes the code that's called when files are dropped on its icon:
func application(_ application: NSApplication, open urls: [URL]) {
// checks to make sure requirements are fulfilled,
// then calls the file import method
}
Am I using the wrong method for this functionality, or is there something else I'm doing wrong? In other words, how do I allow importing/opening a file via dropping it on the app icon without generating unwanted new window in a single-window app?
Upvotes: 0
Views: 146
Reputation: 201
I found the solution in a comment added to an answer I found linked to my question. The solution found at SwiftUI's application(_ openFile:) never called when opening a file from Finder was to add the
.handlesExternalEvents(matching: [])
modifier to the WindowGroup block in my App struct.
Upvotes: 0