![](/img/trans.png)
[英]How to access all the iCloud drive files (outside app container) without UIDocumentPickerViewController?
[英]How to grant file system access outside of container?
根據Apple 的文檔,對於要在其容器之外以及此處列出的目錄之外訪問文件系統的應用程序,它需要指定文件訪問臨時例外權利。
我的應用程序需要讀取和寫入~/Library/Application Support/
一些文件,所以我將com.apple.security.temporary-exception.files.home-relative-path.read-write
值設置為/Library/Application Support/
在應用程序的.entitlement
plist 中。
現在我的應用程序能夠從~/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"}}
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/
。
我的問題:如何在不硬編碼路徑的情況下授予我的應用程序訪問其容器外的文件系統的權限?
我之前關於同一主題的問題已被標記為該問題的重復。 但是,“重復”問題是關於硬編碼路徑,而我的問題是關於非硬編碼路徑。 此外,“重復”的問題是在 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>
是的,這是一條絕對路徑,但它是一個非常簡單和通用的路徑。
let applicationSupportFolder = "/Users/\(NSUserName())/Library/Application Support"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.