首页 > 解决方案 > 如有必要,使用 Finder 提示用户权限打开下载目录

问题描述

我正在构建一个 BitTorrent 客户端,在该客户端中,我通过上下文菜单为用户提供一个选项,以打开 torrent 的包含目录。

为此,我尝试使用如下实例open(_)的方法:NSWorkspace

NSWorkspace.shared.open(directory)

指向目录directory的实例在哪里,如下所示:URL

let directory = URL(fileURLWithPath: item.parentPath, isDirectory: true)

这里,item.parentPath是一个保存绝对路径的字符串。

现在,让我澄清一下代码运行良好。它成功地在 Finder 中打开了我想要的目录(因为它是打开目录的默认应用程序)。

但是,如果该目录恰好是用户的Downloads目录,则会显示以下提示:

由于缺少权限,操作被拒绝。

同样,这没关系,因为我的应用程序没有打开下载目录的权限。但是,我想尝试打开目录,请求许可,就像 macOS 上的任何其他应用程序一样,如下所示:

提示许可。

我在文档中查找并找到了这种方法NSWorkspace: open(_:withApplicationAt:configuration:completionHandler:)。我认为这很棒,因为我可以将实例的promptsUserIfNeeded属性设置为true,我相信这应该让我的应用程序在需要时礼貌地请求打开目录的权限。NSWorkspace.OpenConfiguration

这是我的结果代码:

let url = URL(fileURLWithPath: item.parentPath, isDirectory: true)

let configuration: NSWorkspace.OpenConfiguration = NSWorkspace.OpenConfiguration()
configuration.promptsUserIfNeeded = true

let finder = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "com.apple.finder")

// Open file with default application
NSWorkspace.shared.open([url], withApplicationAt: finder!, configuration: configuration)

可悲的是,它没有任何区别。我仍然得到与第一张图片相同的对话框。

我想知道两件事:

  1. 我究竟做错了什么?
  2. 如何打开目录,必要时提示权限?

标签: swiftxcodemacoscocoaappkit

解决方案


我假设您希望这一切都在沙盒中很好地发挥作用。你有两个选择:

  1. 使用activateFileViewerSelecting(_:)selectFile(_:inFileViewerRootedAtPath:)open(_:withApplicationAt:configuration:completionHandler:)其中任何一个都会提示您获得许可,并且一旦获得许可,如果您愿意,您可以返回使用。

  2. 使用安全范围的书签和持久资源访问


推荐阅读