【问题标题】:Swift on MacOS: cannot open a file from my appMacOS 上的 Swift:无法从我的应用程序中打开文件
【发布时间】:2020-07-12 00:42:03
【问题描述】:

我正在编写一个应用程序,它在 NSTableView 中显示 PDF 文件列表,用户应该能够双击以在默认应用程序(Preview、Adobe Reader...)中打开。

我尝试过使用NSWorkspace.shared.openFileNSWorkspace.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”的权限。这是截图:

Finder error

我不明白我做错了什么。最终我可以在我的应用程序中构建一个轻量级的 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


【解决方案1】:

您必须使用URLinit(fileURLWithPath:) 而不是通常的init?(string:) 来构造文件的URL

let url = URL(fileURLWithPath: "/path/to/file.pdf") 

然后你可以使用NSWorkspace.open实例方法使用默认应用程序打开它

NSWorkspace.shared.open(url)

【讨论】:

  • 感谢您的回答。我得到的错误窗口与我的第二个代码 sn-p 完全相同。
猜你喜欢
  • 2019-07-07
  • 2018-09-11
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多