如何从 Swift 中的字符串路径访问安全范围资源?

How to access a Security Scoped Resource from a String Path in Swift?

我目前正在使用 flutter 将有效文件路径的 String 传递给 Swift 以获得对 安全范围资源的访问权限 (这部分可能不相关)

所以我有一个接受 String 的函数,如下所示:

public func requestAccessToFile(filePath: String) -> Bool {
  let fileUrl = URL(fileURLWithPath: filePath)
  return fileUrl.startAccessingSecurityScopedResource()
}

我知道 startAccessingSecurityScopedResource 并不总是 returns true 但在这种情况下,它应该,因为如果我尝试访问文件而不返回 true 我获取权限错误。

更多上下文:如果我在从文件选择器中获得 URL 后立即尝试调用 startAccessingSecurityScopedResource,它会成功,但如果我使用它的函数来调用它失败(请注意,该函数是用 String 调用的,我传递的路径没有 file:// 协议。例如 "/private/var/mobile/Library/Mobile Documents/com~苹果~CloudDocs/Documents/afile.pdf"

所以我猜测文件选择器创建的 URL 与我使用字符串路径创建的文件有些不同。但不确定。

提前感谢您的帮助。

UIDocumentPickerViewController 提供安全范围的 URL 来访问资源,并且不可能从字符串路径进行相同的访问:

If you need a security-scoped URL’s path as a string value (as provided by the path method), such as to provide to an API that requires a string value, obtain the path from the URL as needed. Note, however, that a string-based path obtained from a security-scoped URL does not have security scope and you cannot use that string to obtain access to a security-scoped resource. https://developer.apple.com/documentation/foundation/nsurl

如果您需要在代码中保存或共享受保护资源的位置,您应该使用书签:

// Get bookmark data from the provided URL
let bookmarkData = try? pickedURL.bookmarkData()
if let data = bookmarkData {
    // Save data
    ...
}

...

// Access to an external document by the bookmark data
if let data = bookmarkData {
    var stale = false
    if let url = try? URL(resolvingBookmarkData: data, bookmarkDataIsStale: &stale),
       stale == false,
       url.startAccessingSecurityScopedResource()
    {
        var error: NSError?
        NSFileCoordinator().coordinate(readingItemAt: url, error: &error) { readURL in
            if let data = try? Data(contentsOf: readURL) {
                ...
            }
        }
        
        url.stopAccessingSecurityScopedResource()
    }
}