swift - 如有必要,使用 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)
可悲的是,它没有任何区别。我仍然得到与第一张图片相同的对话框。
我想知道两件事:
- 我究竟做错了什么?
- 如何打开目录,必要时提示权限?
解决方案
我假设您希望这一切都在沙盒中很好地发挥作用。你有两个选择:
使用
activateFileViewerSelecting(_:)
或selectFile(_:inFileViewerRootedAtPath:)
。open(_:withApplicationAt:configuration:completionHandler:)
其中任何一个都会提示您获得许可,并且一旦获得许可,如果您愿意,您可以返回使用。
推荐阅读
- python - 如何从分配给 KivyMD Python 中的 MDLists 的 TextFields 获取数据
- arrays - 我可以扩展 sc_signal 数组的边界吗?
- flutter - How to increase the display speed of flutter page
- jquery - 实体化表单不适用于动态绑定
- c# - 只允许向上滑动
- javascript - 如何确定变量 BehaviorSubject 与否?
- react-native - 如何获取对用于在 iOS 中通过链接打开我的应用程序的 URL 的引用
- mvvm - RxSwift 处理单元格动作
- javascript - 在这个主要对象中,我如何获得所有汽车型号值
- flutter - Flutter 闪屏动画