【问题标题】:Sync files in the documents directory across devices跨设备同步文档目录中的文件
【发布时间】: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 跨设备同步数据。

【问题讨论】:

    标签: swift core-data cloudkit


    【解决方案1】:

    解决方案是将图像保存在 iCloud Drive 中。

    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")!

    就是这样。超级简单。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-31
      • 1970-01-01
      • 2011-07-26
      • 2013-06-24
      • 2019-10-26
      • 2019-08-05
      • 2014-02-23
      相关资源
      最近更新 更多