如何从基于 SwiftUI 文档的应用程序将多个文件保存在包文件夹中?

问题描述

我正在开发一个基于 SwiftUI 文档的应用程序,其中包含一些易于序列化的数据和多个图像。我想将文档保存为一个包(即文件夹),其中一个文件包含易于序列化的数据,一个文件夹包含作为单独文件的图像。我的包目录应该是这样的:

 <UserChosenName.pspkg>/.    // directory package containing my document data and images
       PhraseSet.dat   // regular file with serialized data from snapshot
       Images/              // subdirectory for images (populated directly from my app as needed)
             Image0.png
             Image1.png
             ....

我创建了一个 FileWrapper 子类,用于设置目录结构并适当添加序列化快照,但是当我在 iOS 模拟器中运行该应用程序并单击“+”创建一个新文档时,该应用程序通过 PkgFileWrapper init 运行() 和 write() 没有错误,但返回到浏览器窗口而没有明显创建任何内容。我已经声明导出和导入的类型标识符符合“com.apple.package”。任何人都可以建议一种方法来让这个工作吗?

PkgFileWrapper 类如下所示:

class PkgFileWrapper: FileWrapper {

var snapshot: Data

init(withSnapshot: Data) {
    self.snapshot = withSnapshot
    let sWrapper = FileWrapper(regularFileWithContents: snapshot)
    let dWrapper = FileWrapper(directoryWithFileWrappers: [:])
    super.init(directoryWithFileWrappers: ["PhraseSet.dat" : sWrapper,"Images" : dWrapper ])
    
    // NOTE: Writing of images is done outside
    // of the ReferenceFileDocument functionality.
}
    
override func write(to url: URL,options: FileWrapper.WritingOptions = [],originalContentsURL: URL?) throws  {
    if let fileWrappers = fileWrappers {
        for (_,wrapper) in fileWrappers {
            try wrapper.write(to: url,options: options,originalContentsURL: originalContentsURL)
        }
    }
}

required init?(coder inCoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}

解决方法

解决方案是不覆盖 PkgFileWrapper.write(...)。如果在 init(...) 中正确设置了目录结构,则会自动创建文件和目录。上面覆盖的 write(...) 函数错误地使用了网址。