【发布时间】:2020-09-24 13:36:57
【问题描述】:
我已经添加了将图像添加到现有的功能,它使用 CoreData 和 CloudKit 来保存和跨设备同步数据。 由于图片比较大,所以我把图片存放在documents目录中,文件名保存在CoreData中。
// "imgData" is the jpeg data of the image
// create a unique name for the file
let date1 = String( Date.timeIntervalSinceReferenceDate )
let imageName = date1.replacingOccurrences(of: ".", with: "-") + ".jpeg"
// get the path to the documents directory
let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
do {
let filePath = path.appendingPathComponent(imageName)
try imgData.write(to: filePath) // save image data to documents directory
} catch {
......
}
// then I store the "imageName" to CoreData
let newRecord = EntityName(context: moc)
newRecord.imgName = imageName
.....
do {
try self.moc.save()
} catch {
print(error)
}
然后我使用以下代码从保存的图像名称中显示图像(在 SwiftUI 中)。
Image(uiImage: UIImage(contentsOfFile: path.appendingPathComponent(entityName.imgName!).path) ?? UIImage())
当我删除并重新安装应用程序或在另一台设备上安装应用程序时,该应用程序可以从 iCloud 获取所有数据(包括图像的文件名)。 但是所有的图像数据都没有了。
那么如何跨设备同步文档目录中的所有文件,例如 CloudKit 跨设备同步数据。
【问题讨论】: