首页 > 解决方案 > 从 MSOffice 应用程序保存新文档时,NSFileProvider importDocument 提供空文件的 fileURL

问题描述

我正在尝试在 Word.app 中创建一个新文档并通过 FileProvider 扩展名保存到我的应用程序中。我对适当方法的实现是:

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

显然,当我通过po FileManager.default.attributesOfItem(forPath: fileURL.path)命令放置断点并检查文件属性时,NSFileSize 的值为 0。命令po FileManager.default.contents(atPath: fileURL.path)返回 0 字节数据和 0x000000000000bad0 指针。写入 internalUrl 的文件也是空的。

最奇怪的是,这种情况只发生在 MS Word、Excel 和 PowerPoint 应用程序中。从 PSPDFKit、文件或照片保存的文件的相同代码可以完美运行。另一方面,Word 正确地将文件保存到 Dropbox 等其他文件提供程序,因此问题不应该存在。

我试图用文件协调器来做到这一点,但这没有帮助。我已经验证每个 startAccessingSecurityScopedResource() 都有它的 stopAccessingSecurityScopedResource()。我已经在两台 iOS11.3 设备上进行了测试 - 相同的行为。我什至发现了其他执行相同操作的开源应用程序。

除了期望 iOS 应用程序扩展工作之外,我做错了什么?

标签: iosswiftios11fileprovider-extension

解决方案


因为Word应用会触发多次importDocument...

在第一次 importDocument 调用时,它尝试在文件提供程序扩展上创建空文件。这就是导入文件的大小为0的原因。

如果你处理得好,Word应用程序将获取保存的文件路径并更新其上的文件。然后它将触发下一个 itemChangedAtURL: api 与它刚刚获得的文件路径。


推荐阅读