【问题标题】:How to grant file system access outside of container?如何授予容器外的文件系统访问权限?
【发布时间】: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 中。

【问题讨论】:

    标签: swift xcode macos sandbox


    【解决方案1】:

    /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>
    

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

    【讨论】:

    • 谢谢。我只是在我的代码中尝试过,但它对我不起作用。将com.apple.security.temporary-exception.files.absolute-path.read-write 添加到权利plist 是您为使其对您有用所做的唯一事情吗?
    • 是的以及包含该字符串的数组。
    • 另外,如果你只是想进入~/Library而不知道绝对路径,你可以在编程中通过使用运行时将返回的容器内数据路径视为HOME并将终止符滑过从末尾去掉后缀。当然要小心意外截断。
    • @mica 不,我相信这种能力需要在典型的安全运行时环境中获得协同设计权利。
    【解决方案2】:

    我遇到了类似的问题。 我将访问容器文件夹之外的内容。 这对我有帮助

    let applicationSupportFolder = "/Users/\(NSUserName())/Library/Application Support"
    

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2012-02-22
    • 2019-06-10
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 2012-07-23
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多