SwiftUI-Cloudkit

Cloudkit with CoreData

  1. Signing & Capabilities 中添加 iCloud(xcode需要开发者账户)。勾选 CloudKit,添加一个命名空间。

  2. Signing & Capabilities 中添加 Background Mode 。勾选 Remote notification

  3. 创建 创建 CoreData 描述文件 xxx.xcdatamodeld。创建 Entry。添加属性。

  4. 将创建 CoreData 时的 NSPersistentContainer。替换成 NSPersistentCloudKitContainer。

  5. 增加同步设置

1
2
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
  1. 完成。

CoreDataManager (with cloudkit)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentCloudKitContainer(name: "xxx") // 此处为 xxx.xcdatamodeld 的名字
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

guard let containerStoreDescription = container.persistentStoreDescriptions.first else {
fatalError("\(#function): Failed to retrieve a persistent store description.")
}
containerStoreDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)

return container
}()

var context : NSManagedObjectContext{
return persistentContainer.viewContext
}

注意: 在 debug 和 release 都添加 Capabilities

文章来自: http://hanks-zyh.github.io/