NSFileProvider importDocument provides fileURL of empty file when saving new document from MSOffice apps

487 Views Asked by At

I'm trying to create a new document in Word.app and save to my app via FileProvider extension. My implementation of appropriate method is:

    override func importDocument(at fileURL: URL,
                                 toParentItemIdentifier parentItemIdentifier: NSFileProviderItemIdentifier,
                                 completionHandler: @escaping (NSFileProviderItem?, Error?) -> Void)
    {

        let internalUrl = NSFileProviderManager.default.documentStorageURL.appendingPathComponent(fileURL.lastPathComponent, isDirectory: false)

        guard fileURL.startAccessingSecurityScopedResource() else { fatalError() }
        try! FileManager.default.copyItem(at: fileURL, to: internalUrl) // breakpoint here
        fileURL.stopAccessingSecurityScopedResource()

        // update local db, whatever

        completionHandler(TemporaryItem(forImporting: internalUrl, into: parentItemIdentifier), nil)
    }

Apparently, when I'm putting the breakpoint and inspecting file attributes via po FileManager.default.attributesOfItem(forPath: fileURL.path) command, value for NSFileSize is 0. Command po FileManager.default.contents(atPath: fileURL.path) returns me 0 byte Data with 0x000000000000bad0 pointer. The file being written to internalUrl is empty as well.

The strangest thing is that this situation happens only with MS Word, Excel and PowerPoint apps. Same code for files saved from PSPDFKit, Files or Photos works perfectly. On the other side, Word correctly saves files to other file providers like Dropbox, so the problem should not be there.

I've tried to do that with file coordinator, but that didn't help. I've verified that every startAccessingSecurityScopedResource() has it's stopAccessingSecurityScopedResource(). I've tested on two iOS11.3 devices - same bahavior. I've even found other open source application which does same operations.

What am I doing wrong except expecting iOS app extension to work?

1

There are 1 best solutions below

0
On

Because the the Word app will trigger several times of importDocument...

At first importDocument calling, it tries to create empty file on file provider extension. That's why the size of imported file is 0.

If you handle it well, the Word app will get the saved file path and update the file on it. And then it will trigger next itemChangedAtURL: api with the file path it just got.