跨设备同步文档目录中的文件

问题描述

添加了向现有映像添加图像的功能,该功能使用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之类的设备之间同步document目录中的所有文件?在设备之间同步数据。

解决方法

解决方案是将图像保存在iCloud驱动器中。

Follow the instructions of this article

然后(按照上述文章的说明进行操作),通过替换此内容来更改文档目录的路径

//获取文档目录的路径
let path = FileManager.default.urls(for: .documentDirectory,in: .userDomainMask).first!

与此 let path = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents")!

就是这样。超级简单。