Swift:如何使用关联的应用程序打开文件?

标签 swift

我喜欢在 macOS 上使用 Excel 打开 .xls 文件。 我只找到了 C# 的示例,但没有找到 Swift 的示例。

额外的问题:即使此文件扩展名与 Excel 无关,是否也可以使用 Excel 启动该文件?

最佳答案

NSWorkspace.sharedWorkspace().openURL(fileURL)NSWorkspace.sharedWorkspace().openFile(fileURL.path!) 以便通过它们打开文件默认应用程序。

如果要强制使用 Excel,可以使用 NSWorkspace.sharedWorkspace().openFile(fileURL.path!, withApplication: "Microsoft Excel")

如果您更喜欢强制使用 Excel 并使用 URL 对象,则有过多的 openURLs(_:withAppBundleIdentifier:options:additionalEventParamDescriptor:launchIdentifiers)

虽然这没什么大不了的,但我正在根据 Swift 4.2 更新语法 -

NSWorkspace.shared.openFile(fileURL!.path)
NSWorkspace.shared.openFile(fileURL!.path, withApplication: "Microsoft Excel")
NSWorkspace.shared.open([fileURL!], withAppBundleIdentifier: "com.microsoft.Excel", options: NSWorkspace.LaunchOptions.withErrorPresentation, additionalEventParamDescriptor: nil, launchIdentifiers: nil)

要获取任何应用程序的 Bundle Identifier,请在您的终端中使用此命令

 osascript -e 'id of app "*app_name*"'

关于Swift:如何使用关联的应用程序打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37956052/

相关文章:

ios - CAShapeLayer 未出现在图层 subview 上

arrays - Swift - 将 url 内容排序到数组中

swift - 本地化不同语言的数字整数

ios - 如何检查用户是否在文本字段中输入了多于一位小数?

ios - UITableViewCell 的内容 View 高度未针对动态字体进行调整(NSLayoutConstraints)

ios - 如何将 UIControl 作为函数参数传递?

ios - Swift 4.2 - Cocoapods : Adding and accessing scnassets in resource_bundles

ios - 如何使用搜索在Swift中搜索多个字段?

ios - Swift 2阶段初始化安全检查4

swift - NSColor.init?(cgColor : aCGColor) ambiguous reference