Core Data+CloudKit无法同步或连接CloudKit问题排查求助
检查Core Data实体的CloudKit开关
打开你的Core Data模型文件,选中每个实体,在右侧检查器的「CloudKit」板块,确保勾选了「Use with CloudKit」。现有项目加CloudKit时,这个选项默认是关闭的,很容易漏掉。确认模拟器的iCloud登录状态
两个模拟器必须登录同一个Apple ID,并且在模拟器的「设置-Apple ID-iCloud」里开启「iCloud Drive」。有时候模拟器会莫名登出,或者默认没登录,直接导致同步失败。手动指定CloudKit容器ID
自动配置偶尔会出问题,你可以在代码里手动指定容器ID,确保和Xcode能力配置里的一致。修改你的persistentContainer代码:lazy var persistentContainer: NSPersistentCloudKitContainer = { let container = NSPersistentCloudKitContainer(name: "CloudTest") // 手动指定CloudKit容器ID guard let storeDescription = container.persistentStoreDescriptions.first else { fatalError("找不到持久化存储描述") } storeDescription.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.你的BundleID") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) container.viewContext.automaticallyMergesChangesFromParent = true return container }()检查iCloud控制台的环境
Xcode默认用的是开发环境,去iCloud控制台查看数据时,要切换到「开发」标签页,别跑到生产环境里找数据。确认数据保存时的上下文操作
确保你修改数据后调用了try? persistentContainer.viewContext.save(),本地数据只有成功持久化后,才会触发CloudKit同步。另外,保存时最好加错误捕获,看看有没有隐藏的保存失败问题。检查后台模式的具体选项
在Xcode的「Signing & Capabilities」里,Background Modes除了勾选「Remote notifications」,还要确保「Background fetch」也被勾选,这能提升CloudKit同步的可靠性。手动触发同步测试
有时候同步不会立刻触发,可以试试调用persistentContainer.refreshAllObjects(),或者重启模拟器,甚至在模拟器的「设置-iCloud」里手动拉取同步。
内容的提问来源于stack exchange,提问作者Medicine Man

