如何授予容器外部文件系统访问权限?

时间:2020-02-18 22:40:27

标签: swift xcode macos sandbox

根据Apple's documentation,要使应用访问其容器外部和列出的目录here之外的文件系统,它需要指定文件访问临时例外权利。

我的应用需要在~/Library/Application Support/中读写文件,因此我在应用的com.apple.security.temporary-exception.files.home-relative-path.read-write plist中将/Library/Application Support/的值设置为.entitlement

现在,如果路径是这样硬编码的,我的应用程序便可以从~/Library/Application Support/中读取文件:

let filePath = URL(fileURLWithPath: "/Users/myUsername/Library/Application Support/path/to/somefile.txt")
let fileContent = try! String(contentsOf: filePath, encoding: .ascii)

但是,如果我像下面这样操作,它将无法正常工作:

let filePathString = "~/Library/Application Support/path/to/somefile.txt"
let expandedFilePathString = NSString(string: filePathString).expandingTildeInPath
let filePath = URL(fileURLWithPath: expandedFilePathString)
let fileContent = try! String(contentsOf: filePath, encoding: .ascii) // Error

// alternatively
let applicationSupportPath = try! FileManager.default.url(
    for: .applicationSupportDirectory,
    in: .userDomainMask,
    appropriateFor: nil,
    create: false
)
let filePath = applicationSupportPath.appendingPathComponent("path/to/somefile.txt")
let fileContent = try! String(contentsOf: filePath, encoding: .ascii) // Error

这两个错误都是因为该应用正在尝试访问容器中的路径:Error Domain=NSCocoaErrorDomain Code=260 "The file “somefile.txt” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users/myUsername/Library/Containers/my.bundle.id/Data/Library/Application Support/path/to/somefile.txt, NSUnderlyingError=0x600000c71c20 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

此外,FileManager.default.homeDirectoryForCurrentUser返回/Users/myUsername/Library/Containers/my.bundle.id/Data/

我的问题:如何在不对路径进行硬编码的情况下授予我的应用程序对文件系统的访问权,而不是在其容器之外?

同一主题上的

My previous quesion已被标记为this question的重复项。但是,“重复”问题与硬编码路径有关,而我的问题与非硬编码路径有关。另外,“重复”问题在Objective-C中,而我的问题在Swift中。

1 个答案:

答案 0 :(得分:0)

为此,我将axios.defaults.withCredentials = true;赋予/

com.apple.security.temporary-exception.files.absolute-path.read-write

是的,这是一条绝对的道路,但却是一条非常简单且通用的道路。