0

I have an app in the Mac App Store. A customer recently requested that I add a way to run a calculator from within the app via a keyboard shortcut.

I added the following code in the Commands section of my app’s App.Swift file to generate a Calculator menu item, together with an associated shortcut, which is intended to launch the MacOS Calculator app.

Button("Calculator") {
let calendarTask = Process()
calendarTask.launchPath = "/System/Applications/Calculator.app/Contents/MacOS/Calculator"
calendarTask.launch()
}
.keyboardShortcut("=")

Clicking on the Calculator menu item or entering the Cmd + = shortcut launches the macOS Calculator app but the Calculator app crashes on launch. The Crash Report provides the following analysis:

Crashed Thread: 0 Dispatch queue: com.apple.main-thread

Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x000000019948c1d0

Termination Reason: Namespace SIGNAL, Code 5 Trace/BPT trap: 5 Terminating Process: exc handler [10604]

Selecting the Re-Open option of the Crash Report results in the Calculator app relaunching successfully but this is clearly not the right way to go about launching it in the first place!

Setting the calendarTask.launchPath to "/System/Applications/Calculator.app" results in no action; it seems that the launchPath must point to the target app's Unix executable file, rather than its app file, for it to launch. Double clicking on the Calculator executable file launches the Calculator app but as a process within Terminal:

Last login: Fri Mar 17 15:48:29 on ttys003
/System/Applications/Calculator.app/Contents/MacOS/Calculator ; exit;
christopherhull@Hull-Mac-Mini-M1 ~ % /System/Applications/Calculator.app/Contents/MacOS/Calculator ; exit;
2023-03-17 16:28:02.782 Calculator[10953:627082] XType: XTFontStaticRegistry is enabled by Info.plist.

Quitting Terminal halts the process and the Calculator app quits.

Please can somebody tell me how to launch a MacOS app, such as Calculator, from within another app without it crashing?

HangarRash
  • 7,314
  • 5
  • 5
  • 32

1 Answers1

2

Process is the wrong tool here. You want NSWorkspace.shared.openApplication to launch an independent application. Keep in mind that if your app is sandboxed, it may not be allowed to launch other applications. I believe NSWorkspace is allowed, even in a sandbox, but be on the lookout for permission-related issues. See also How to launch another process in sandbox on Mac?

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • Solved! Using NSWorkspace.shared.openApplication worked perfectly, even though my app is sandboxed. I was able to adapt code found at [this answer] (https://stackoverflow.com/questions/27505022/open-another-mac-app/58241536#58241536) very easily; in fact I was able to omit the `configuration.arguments = [path]` statement, because my app is sandboxed and configuration.arguments are ignored in sandboxed 'parent' apps. – Christopher Hull Mar 17 '23 at 23:29