问题
I have this macOS app that is launched at login. This app has a space in the name "My App.app".
For that matter, I have created a helper app that loads at login and launches the main app.
I am inside this helper, trying to launch the main app.
For this reason I need to get the main app path. So, I do:
let appName = "My App.app"
let path = "/Applications/" + appName
let newURL = NSURL.fileURL(withPath: path)
when I try to use this
let app = try NSWorkspace.shared.launchApplication(at: newURL,
options:[.withErrorPresentation, .inhibitingBackgroundOnly, .async],
configuration: [:])
I get an error "APPLICATION NOT FOUND".
One of the problems is that the App contains a space in the name "My App.app". I remove the space in the app name and this command successfully launches the app.
But I need the space in the name.
Then I try to launch the app using the bundle identifier.
NSWorkspace.shared.launchApplication(withBundleIdentifier: mainAppBundleIdentifier,
options: [.withErrorPresentation, .inhibitingBackgroundOnly, .async],
additionalEventParamDescriptor: nil,
launchIdentifier: nil)
then I get another error,
MyApp can’t be opened. Move “My App” to the Applications folder and try again.
The problem is that the app is already on the Applications folder.
then I use this, just to check
let path = NSWorkspace.shared.absolutePathForApplication(withBundleIdentifier: mainBundleId)
and I get this
"/Users/myself/Library/Mail/V6/0982138471-EA33/[Gmail].mbox/All Mail.mbox/871628745618726547816A/Data/2/8/5/Attachments/582584/2/MyAppMac.app"
WTF!!??
Two things wrong about this:
- This is a link to an email I have sent yesterday to a tester, sending him the application.
- The app mentioned in the link is MyAppMac.app that is the Xcode target name, without localization.
How in the heavens name do I launch an app from another app when the app contains a space in the name and is localized?
How do I get the target name?
回答1:
The usual way to launch the main application is first to check if it's already running and if not to run the executable and pass a variable to inform the main application that it was launched by the helper
For example
func applicationDidFinishLaunching(_ aNotification: Notification) {
let appName = "Foo"
let bundleIdentifier = "com.spacedog.foo"
if NSRunningApplication.runningApplications(withBundleIdentifier: bundleIdentifier).isEmpty {
let bundleURL = Bundle.main.bundleURL
var pathComponents = bundleURL.pathComponents
pathComponents.removeLast(3)
pathComponents.append(contentsOf: ["MacOS", appName])
let mainAppURL = NSURL.fileURL(withPathComponents:pathComponents)!
let options = [NSWorkspace.LaunchConfigurationKey.arguments : ["launchedAtLogin"]]
_ = try? NSWorkspace.shared.launchApplication(at: mainAppURL as URL, options: .withoutActivation, configuration: options)
}
NSApp.terminate(nil)
}
来源:https://stackoverflow.com/questions/57786493/macos-impossible-to-launch-an-app-with-localized-name-and-space