如何访问 macOS 上沙盒应用程序中的文件系统?

问题描述 投票:0回答:1

想象一下 macOS 上的沙盒应用程序(因此,精通应用程序故事),您可以将文件拖放到其中,随后将对其进行处理和写回。显然,应用程序需要沙箱外的写入权限。 我该怎么做?

更简洁地说:应用程序将通过调用 shell 脚本来处理这些文件。执行 shell 脚本很容易,但也需要相应提升其权限,这可能是一个安全问题。 这可能吗?

swift macos sandbox
1个回答
0
投票

解决方案:您需要向用户呈现一个文件选择器面板(例如通过 SwiftUI 中的 .fileImporter),以便用户可以主动选择文件夹。该文件夹(及其子文件夹)将临时添加到应用程序的沙箱中。 但是,为每个新应用程序启动都执行此操作会很麻烦。 macOS 允许您将从 FileOpenPanel 返回的 URL 保存为书签:

// directory -> URL returned from the .fileImporter
let bookmark = try directory.bookmarkData(options: .withSecurityScope)
UserDefaults.standard.set(bookmark, forKey: "bookmark")

如果您

,后续应用程序启动将具有相同的提升权限
var theBookmarkData = UserDefaults.standard.data(forKey: "bookmark")
var stale = false // Does the bookmark need a refresh?
let bookmarkURL = try URL(resolvingBookmarkData: theBookmarkData!, options: .withSecurityScope, bookmarkDataIsStale: &stale )
if stale {
    theBookmarkData = try bookmarkURL.bookmarkData(options: .withSecurityScope)
    UserDefaults.standard.set(theBookmarkData, forKey: "bookmark")
}
let gotAccess = bookmarkURL.startAccessingSecurityScopedResource()
...
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.