天天看点

2# 使用CloudKit私有数据,实现跨设备同步

作者:SwiftTang
私有数据库的应用场景是iCloud用户跨设备使用自己的数据,和Apple自带记事本一样,数据可以在iMac、Macbook、iPhone、iPad等Apple设备之间同步。
  • 数据可以自动同步,各个设备上数据一致;
  • 即使在某台设备删掉应用,数据也不会丢失
  • 要求使用者设备必须使用同一iCloud帐户登录;
  • 私有数据只有用户自己使用,别的用户无法访问。
私有数据库使用与CoreData开发完全一样,无需额外操作;下面以体重记录为例,看如何快速使用CloudKit私有数据库:

第1步: 建模

2# 使用CloudKit私有数据,实现跨设备同步

image.png

第2步:配置共享

2# 使用CloudKit私有数据,实现跨设备同步

image.png

第3步:添加数据

与CoreData操作一样,CloudKit自动同步,无需额外操作。

func saveWeight(){
        let context = PersistenceController.shared.container.newBackgroundContext()
        let newRecord = Weight(context: context)
        guard let weightValue = Double(weight) else { return }
        newRecord.date = Date()
        newRecord.kilogram = weightValue
        do{
            try context.save()
        }catch{
            print("保存失败")
        }
    }           

第4步:跨设备查看数据

依然与本地CoreData操作一样。

@FetchRequest(entity: Weight.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Weight.date, ascending: false)])
    var items: FetchedResults<Weight>           

在登录icloud帐号后,各个设备数据一致。

2# 使用CloudKit私有数据,实现跨设备同步

image.png

继续阅读