ios - 从 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 应用程序扩展工作之外,我做错了什么?
解决方案
因为Word应用会触发多次importDocument...
在第一次 importDocument 调用时,它尝试在文件提供程序扩展上创建空文件。这就是导入文件的大小为0的原因。
如果你处理得好,Word应用程序将获取保存的文件路径并更新其上的文件。然后它将触发下一个 itemChangedAtURL: api 与它刚刚获得的文件路径。
推荐阅读
- .net - 如何从 Azure Devops 在 60 个 AWS 服务器上部署代码
- docker - 如何从 docker hub 获取开放自由映像的稳定版本?
- sql - 是否有任何 SQL 查询或 OIM API 在禁用用户时输入理由?
- java - logback.xml 中的日志名称问题
- go - 如何在go中从jwk生成pem
- flutter - Flutter 注销并漂亮地替换堆栈
- java - Quartz为已经存在的工作添加触发器
- javascript - 为什么我的 api json 数据无法从循环中读取我的属性并将 html 数据附加到 dom?
- node.js - 向我的网站添加身份验证挑战逻辑
- css - 如何使用 Angular 6 将 html 字符串呈现到 div