想象一下 macOS 上的沙盒应用程序(因此,精通应用程序故事),您可以将文件拖放到其中,随后将对其进行处理和写回。显然,应用程序需要沙箱外的写入权限。 我该怎么做?
更简洁地说:应用程序将通过调用 shell 脚本来处理这些文件。执行 shell 脚本很容易,但也需要相应提升其权限,这可能是一个安全问题。 这可能吗?
解决方案:您需要向用户呈现一个文件选择器面板(例如通过 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()
...