我有这个在登录时启动的 macOS 应用程序。此应用程序的名称“My App.app”中有一个空格。
就此而言,我创建了一个帮助程序应用程序,该应用程序在登录时加载并启动主应用程序。
我在这个助手内部,尝试启动主应用程序。
因此,我需要获取主应用程序路径。所以,我这样做:
let appName = "My App.app"
let path = "/Applications/" + appName
let newURL = NSURL.fileURL(withPath: path)
当我尝试使用这个时
let app = try NSWorkspace.shared.launchApplication(at: newURL,
options:[.withErrorPresentation, .inhibitingBackgroundOnly, .async],
configuration: [:])
我收到错误“找不到应用程序”。
问题之一是应用程序名称“My App.app”中包含空格。我删除了应用程序名称中的空格,此命令成功启动了应用程序。
但我需要名称中的空格。
然后我尝试使用包标识符启动应用程序。
NSWorkspace.shared.launchApplication(withBundleIdentifier: mainAppBundleIdentifier,
options: [.withErrorPresentation, .inhibitingBackgroundOnly, .async],
additionalEventParamDescriptor: nil,
launchIdentifier: nil)
然后我收到另一个错误,
MyApp can’t be opened. Move “My App” to the Applications folder and try again.
问题是该应用已经位于“应用程序”文件夹中。
然后我用这个,只是为了检查
let path = NSWorkspace.shared.absolutePathForApplication(withBundleIdentifier: mainBundleId)
我明白了
"/Users/myself/Library/Mail/V6/0982138471-EA33/[Gmail].mbox/All Mail.mbox/871628745618726547816A/Data/2/8/5/Attachments/582584/2/MyAppMac.app"
什么鬼!!!?
这里有两点错误:
- 这是我昨天发送给测试人员的电子邮件链接,向他发送了申请。
- 链接中提到的应用程序是 MyAppMac.app,它是 Xcode 目标名称,未进行本地化。
当应用程序名称中包含空格并且已本地化时,我该如何从另一个应用程序启动该应用程序?
如何获取目标名称?
最佳答案
启动主应用程序的通常方法是首先检查它是否已经在运行,如果没有运行可执行文件并传递一个变量来通知主应用程序它是由助手启动的
例如
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)
}
关于xcode - macOS - 无法启动具有本地化名称和空间的应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57786493/