'SwiftUI cannot read data of Document using .fileImporter - Error Domain=NSCocoaErrorDomain Code=257

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



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dilan