NSWorkspace 有 https://developer.apple.com/documentation/appkit/nsworkspace/1534059-runningapplications,它返回 NSRunningApplication 的列表。
NSRunningApplication
提供了icon
、bundleURL
、executableURL
等,以及terminate()
等方法。
我正在为其他已安装但未运行的应用程序寻找同样的东西。
我知道
system_profiler SPApplicationsDataType
返回应用程序列表,但它没有提供我需要的信息。
您可以枚举 /Applications 目录、/System/Applications 目录、~/Applications 目录或您认为“已安装”应用程序所在的任何其他位置中的文件。
guard let enumerator = FileManager.default.enumerator(
at: URL(filePath: "/Applications"),
includingPropertiesForKeys: nil,
options: [.skipsPackageDescendants]
) else { return }
for case let url as URL in enumerator {
// ...
}
假设所有“应用程序”都有一个捆绑包(简单的可执行文件没有),您可以尝试从中创建一个
Bundle
并获取您需要的信息。
guard let bundle = Bundle(url: url) else { continue }
print(bundle.executableURL)
print(bundle.bundleIdentifier)
print(bundle.infoDictionary)
使用
infoDictionary
访问其 Info.plist 文件中的密钥。请参阅此处可用的按键。
要获取图标,您可以执行以下操作:
if let dict = bundle.infoDictionary,
let iconName = dict["CFBundleIconFile" /* or CFBundleIconName for newer versions*/] as? String,
let url = bundle.urlForImageResource(iconName) {
NSImage(contentsOf: url) // or whatever else you want...
}