xcode - macOS - 无法启动具有本地化名称和空间的应用程序
问题描述
我有这个在登录时启动的 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 无法打开。将“我的应用程序”移动到应用程序文件夹,然后重试。
问题是该应用程序已经在 Applications 文件夹中。
然后我用这个,只是为了检查
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)
}