【发布时间】:2020-02-18 22:40:27
【问题描述】:
根据Apple's documentation,要让应用程序访问其容器之外的文件系统,以及here 列出的目录之外的文件系统,它需要指定文件访问临时例外权利。
我的应用需要读写~/Library/Application Support/中的一些文件,所以我在应用的.entitlement plist中将com.apple.security.temporary-exception.files.home-relative-path.read-write的值设置为/Library/Application Support/。
如果路径是这样硬编码的,现在我的应用程序能够从~/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 中。
【问题讨论】: