gpt4 book ai didi

swift - 使用 Finder 打开下载目录,必要时提示用户许可

转载 作者:行者123 更新时间:2023-12-03 17:37:30 25 4
gpt4 key购买 nike

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

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

NSWorkspace.shared.open(directory)

其中 directory 是指向目录的 URL 实例,如下所示:

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

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

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

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

Operation rejected due to lack of permissions.

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

Prompting for permission.

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

这是我生成的代码:

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. 如何打开目录,并在必要时提示输入权限?

最佳答案

我假设您希望这一切在沙盒中顺利运行。您有两个选择:

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

  2. 使用Security-Scoped Bookmarks and Persistent Resource Access .

关于swift - 使用 Finder 打开下载目录,必要时提示用户许可,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61287061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com