I need to open a .log file programmatically from my macOS app (written in SwiftUI.) I tried the following:
NSWorkspace.shared.launchApplication("/opt/my_log/my.log")
but it doesn’t do anything and I get the following in the debugging console:
2023-03-29 19:09:20.010539+0300 MyApp [94219:6031169] [open] LAUNCH: request execute thru runningboard of 0x0-0xb93b93 (null)//opt/my_log/my.log failed with error=Error Domain=RBSRequestErrorDomain Code=5 "Launch failed." UserInfo={NSLocalizedFailureReason=Launch failed., NSUnderlyingError=0x600001d32bb0 {Error Domain=NSPOSIXErrorDomain Code=111 "Unknown error: 111" UserInfo={NSLocalizedDescription=Launchd job spawn failed}}}
2023-03-29 19:09:20.065015+0300 MyApp [94219:6031169] [open] LAUNCH: Launch failure with -10810/kLSUnknownErr <FSNode 0x6000013f8b40> { isDir = n, path = '/opt/my_log/my.log' }
If I double-click that .log file in Finder it opens it in the Console app:
But how do I open it programmatically?
>Solution :
As the name implies launchApplication expects an URL representing an application.
The API which opens a file using a specific application is
let logURL = URL(fileURLWithPath: "/opt/my_log/my.log")
let consoleURL = URL(fileURLWithPath: "/System/Applications/Utilities/Console.app/")
var configuration = NSWorkspace.OpenConfiguration()
configuration.activates = true
NSWorkspace.shared.open([logURL], withApplicationAt: consoleURL, configuration: configuration)
Side note: If the application is sandboxed you don’t have the permission to open files programmatically outside of the application container.
