File sharing by share extension works on simulator but fails on device

I developed an app with a share extension, and want to receive files shared from other apps by the share extension.

The following is what I do in the share extension.

let attachments = (self.extensionContext?.inputItems.first as? NSExtensionItem)?.attachments ?? []

guard #available(iOSApplicationExtension 14.0, *) else {return}

let contentType = "public.file-url"

for provider in attachments {

    guard provider.hasItemConformingToTypeIdentifier(contentType) else { continue }

    provider.loadItem(forTypeIdentifier: contentType, options: nil) { [unowned self] (data, error) in

        let fileUrl = data as! URL





        // Get shared file data here,

        // works fine on simulator, but the permission error occurs if run on device

        try? Data(contentsOf: fileUrl)

    }
}

self.extensionContext?.completeRequest(returningItems: [], completionHandler: nil)

.

It works fine on simulator, but get an error like below if I read the shared data (using Data(contentsOf: url)) when runs on device.

.

Failed to read file, error Error Domain=NSCocoaErrorDomain Code=257 "The file “[File name]” couldn’t be opened because you don’t have permission to view it." UserInfo={NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/[some ID String]/File Provider Storage/[File name], NSUnderlyingError=0x2800b42a0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

I am running this code on an iPhone 12, iOS 15.3.1. Xcode 13.4.1.

If any further information is needed, please let me know.

Thank you.

File sharing by share extension works on simulator but fails on device
 
 
Q