如何在macOS上通过代码从FileProvider Extension打开文件
在macOS FileProviderUI扩展中打开文件的解决方案
- 使用
NSFileCoordinator获取沙箱授权后的有效URL,再执行打开操作,这是解决沙箱权限问题的核心方法:
let fileCoordinator = NSFileCoordinator() fileCoordinator.coordinate(readingItemAt: itemURL, options: .withoutChanges, error: nil) { authorizedURL in NSWorkspace.shared.open(authorizedURL) }
原理:FileProvider的文件URL需要通过文件协调器获取沙箱内的临时访问授权,直接使用原始URL会因权限不足被系统拦截。
检查扩展的
Info.plist沙箱配置,确保添加了对应文件访问权限:- 若仅需读取,添加
com.apple.security.files.user-selected.read-only - 若需读写,添加
com.apple.security.files.user-selected.read-write
(FileProvider扩展默认会有基础权限,但额外配置可避免权限缺失)
- 若仅需读取,添加
可指定目标应用直接打开文件,绕过Finder上下文的权限限制:
// 示例:用TextEdit打开文件 let targetAppURL = URL(fileURLWithPath: "/Applications/TextEdit.app") NSWorkspace.shared.openApplication(at: targetAppURL, configuration: NSWorkspace.OpenConfiguration()) { app, error in guard let app = app, error == nil else { // 处理打开应用失败的情况 return } app.open([itemURL]) }
内容的提问来源于stack exchange,提问作者mixtly87
相关产品推荐
相关产品推荐

