处理包含多个图像的 UIDocument 中的图像加载/存储

Mau*_*itz 1 nsfilewrapper ios uidocument swift

我有一个简单的模型对象,Location其中包含一些文本项和一个images : [UIImages]?. Location所以Codable我将文本位存储为 JSON,然后将图像写入相同的FileWrapper.

我的问题是如何存储图像文件和 [UIImage] 数组之间的关系。图像必须以相同的顺序返回。有没有办法可以连接到编码,以便数组被指向图像的 URL 替换?

或者,我应该始终将图像作为单独的文件(例如在缓存目录中)并将 [UIImage] 替换为 [URL]

mat*_*att 5

下面是一个在文件包装器中存储一堆图像文件的示例,以及按list特定顺序存储它们名称的“索引”(我称之为 ):

    let fm = FileManager.default
    let docurl = fm.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let d = FileWrapper(directoryWithFileWrappers: [:])
    let imnames = ["manny.jpg", "moe.jpg", "jack.jpg"]
    for imname in imnames {
        let im = UIImage(named:imname)!
        let imfw = FileWrapper(regularFileWithContents: UIImageJPEGRepresentation(im, 1)!)
        imfw.preferredFilename = imname
        d.addFileWrapper(imfw)
    }
    let list = try! JSONEncoder().encode(imnames)
    let listfw = FileWrapper(regularFileWithContents: list)
    listfw.preferredFilename = "list"
    d.addFileWrapper(listfw)
    do {
        try d.write(to: docurl.appendingPathComponent("myFileWrapper"), originalContentsURL: nil)
        print("ok")
    } catch {
        print(error)
    }
Run Code Online (Sandbox Code Playgroud)

下面是一个通过获取列表然后按相同顺序按名称获取图像文件来读取文件包装器的示例:

    let fm = FileManager.default
    let docurl = fm.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let fwurl = docurl.appendingPathComponent("myFileWrapper")
    do {
        let d = try FileWrapper(url: fwurl)
        if let list = d.fileWrappers?["list"]?.regularFileContents {
            let imnames = try! JSONDecoder().decode([String].self, from: list)
            for imname in imnames {
                if let imdata = d.fileWrappers?[imname]?.regularFileContents {
                    print("got image data for", imname)
                    // in real life, do something with the image here
                }
            }
        } else {
            print("no list")
        }
    } catch {
        print(error); return
    }
Run Code Online (Sandbox Code Playgroud)

打印:

got image data for manny.jpg
got image data for moe.jpg
got image data for jack.jpg
Run Code Online (Sandbox Code Playgroud)

您在 UIDocument 中想要做的就是同样的事情,只不过 UIDocument 会为您写入和读取文件包装器。