If you just want to tinker with all the code, you can get it here.
How to make your SwiftUI MacOS app open a file
You can open the file by using “Command + Click” Open With dialog, or you change the file association to use your app as the default app for that file type.
Since my MacOS app is used to open images, the code is for opening image types:
VStack{
//.....
}.onOpenURL(){ url in
if let imageData = try? Data(contentsOf: url) {
DispatchQueue.main.async {
image = NSImage(data: imageData)
}
}
}
Don’t forget to remove the App Sandbox in Xcode so you can access the files in the operating system. Unfortunately this will make your app very unlikely to be accepted in the App Store, but you can still distribute it on your own.
How to make your SwiftUI MacOS App open a file in the same app window
By default, you MacOS app will open a new window each time you open a new file with your program. You rarely will need this, not exactly sure why one would make this behaviour the default, but here is how “fix it”
WindowGroup {
ContentView().preferredColorScheme(.dark)
.handlesExternalEvents(preferring: Set(arrayLiteral: "pause"), allowing: Set(arrayLiteral: "*"))
.frame(minWidth: 300, minHeight: 300)
}
.windowStyle(.hiddenTitleBar)
.commands {
CommandGroup(replacing: .newItem, addition: { })
}.handlesExternalEvents(matching: Set(arrayLiteral: "*"))
Download the FastImage for MacOS source code here.