0

Trying to read data of document using following code block

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

and it gives the following error

Error Domain=NSCocoaErrorDomain Code=257 "The file “a.txt” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/private/var/mobile/Containers/Data/Application/CCB51769-028A-4C15-A2C2-3A263791BA08/Documents/a.txt, NSUnderlyingError=0x283e6a4f0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

This error occurred only on physical device. Xcode 13.2.1 Tested on iOS 15.2 | 14.8

Dilan
  • 2,610
  • 7
  • 23
  • 33

1 Answers1

3

Use 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)
        }
    })

Apple Documentation

Dilan
  • 2,610
  • 7
  • 23
  • 33