Categories
Apple MacOS App Swift SwiftUI

Practical SwiftUI stuff I learned while building a Photo Viewer for MacOS

Photo Viewer for Mac
Photo Viewer for MacOS made using SwiftUI

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.

By Cosmin Dolha

Generalist at the intersection of code, art, and systems—combining 20+ years of software, AI, hardware, and 3D design with a passion for economics, probabilities, and human behavior to turn ideas into working prototypes.