SwiftUI 无法使用 .fileImporter 读取文档数据 - Error Domain=NSCocoaErrorDomain Code=257

Dil*_*lan 0 xcode ios swift swiftui swiftui-fileimporter

尝试使用以下代码块读取文档数据

\n
.fileImporter(isPresented: $showDocPicker, allowedContentTypes: [SupportDocTypes], onCompletion: { result in\n    do {\n        let fileURL = try result.get()\n        let docData  = try Data(contentsOf:fileURL) // <-error on this line\n    } catch {\n        print ("error reading")\n        print (error.localizedDescription)\n    }\n})\n
Run Code Online (Sandbox Code Playgroud)\n

它给出了以下错误

\n
\n

错误域=NSCocoaErrorDomain代码=257“文件\xe2\x80\x9ca.txt\xe2\x80\x9d无法\xe2\x80\x99打开,因为您\xe2\x80\x99没有查看它的权限。” \nUserInfo={NSFilePath=/private/var/mobile/Containers/Data/Application/CCB51769-028A-4C15-A2C2-3A263791BA08/Documents/a.txt,\nNSUnderlyingError=0x283e6a4f0 {错误域=NSPOSIXErrorDomain代码=1\n"不允许操作”}}

\n
\n

此错误仅发生在物理设备上。\nXcode 13.2.1\n在 iOS 15.2 上测试 | 14.8

\n

Dil*_*lan 5

使用startAccessingSecurityScopedResource()

.fileImporter(isPresented: $showDocPicker, allowedContentTypes: [SupportDocTypes], onCompletion: { result in
        do {
            let fileURL = try result.get()
            if fileURL.startAccessingSecurityScopedResource() {
                let docData  = try Data(contentsOf:fileURL) 
                //other codes
            }
            
        } catch {
            print ("error reading")
            print (error.localizedDescription)
        }
    })
Run Code Online (Sandbox Code Playgroud)

苹果文档