根据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中。
将/
赋予com.apple.security.temporary-exception.files.absolute-path.read-write
是我要做的。
<key>com.apple.security.temporary-exception.files.absolute-path.read-write</key>
<array>
<string>/</string>
</array>
是的,这是一条绝对的道路,但这是一条非常简单且通用的道路。