【发布时间】:2020-07-12 00:42:03
【问题描述】:
我正在编写一个应用程序,它在 NSTableView 中显示 PDF 文件列表,用户应该能够双击以在默认应用程序(Preview、Adobe Reader...)中打开。
我尝试过使用NSWorkspace.shared.openFile 和NSWorkspace.shared.open(_: withAppBundleIdentifier: options: additionalEventParamDescriptor: launchIdentifiers:),但它们都不起作用。
我不能使用新的 func open(URL, configuration: NSWorkspace.OpenConfiguration, completionHandler: ((NSRunningApplication?, Error?) -> Void)?),因为它是针对 Catalina 之前的计算机的。
这里是sn-ps的两个代码:
1.
@objc func doubleClickOnResultRow() {
let clickedRow = resultsTableView.selectedRow
if ( clickedRow > -1 ) {
let myURL = foundItems[clickedRow] as URL
if (!NSWorkspace.shared.openFile(myURL.path)) {
print("Unable to open : ", myURL.path)
}
}
}
第一个不执行任何操作,我在控制台中收到“无法打开:url/to/my/file.pdf”。
2.
@objc func doubleClickOnResultRow() {
let clickedRow = resultsTableView.selectedRow
if ( clickedRow > -1 ) {
let myURL = foundItems[clickedRow] as URL
NSWorkspace.shared.open([myURL], withAppBundleIdentifier: "com.apple.Preview", options: NSWorkspace.LaunchOptions.withErrorPresentation, additionalEventParamDescriptor: nil, launchIdentifiers: nil)
}
}
但是,使用这个,当我双击一个文件时,我会看到一个错误窗口,其中包含 Finder 图标,上面写着:
“应用程序“我的应用程序”没有打开“myfile.pdf”的权限。这是截图:
我不明白我做错了什么。最终我可以在我的应用程序中构建一个轻量级的 PDF 查看器,但如果可能的话,我真的很想避免它。
编辑 2020 年 3 月 31 日,16:10
我尝试了第三种方法,用这个 (found here) 调用 shell 命令“打开”:
func shell(_ command: String) -> String {
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", command]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String
return output
}
然后
let command = "open \""+myURL.path+"\""
print(shell(command))
我得到了
LSOpenURLsWithRole() failed with error -54 for the file path/to/my/file.pdf.
【问题讨论】:
标签: swift macos nsworkspace