How do I sync Core Data with CloudKit?

Syncing Core Data with CloudKit allows iOS applications to seamlessly store and sync local data with Apple’s iCloud infrastructure. This integration helps in maintaining data consistency across multiple devices. Below is a basic example explaining how to achieve this synchronization.

// Code example to sync Core Data with CloudKit import CoreData import CloudKit let container = NSPersistentCloudKitContainer(name: "YourDataModel") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } }) // Fetch data from Core Data let fetchRequest: NSFetchRequest = YourEntity.fetchRequest() do { let results = try context.fetch(fetchRequest) // Process results } catch { print("Fetch failed") } // Save data to Core Data let newItem = YourEntity(context: context) newItem.attribute = "New Value" do { try context.save() } catch { print("Save failed") } // Sync with CloudKit let cloudKitContainer = CKContainer.default() let privateDatabase = cloudKitContainer.privateCloudDatabase privateDatabase.fetch(withRecordID: CKRecord.ID(recordName: "yourRecordID")) { record, error in if let error = error { print("Error fetching record: \(error)") } else { // Update Core Data with fetched record // Your synchronization code here } }

Core Data CloudKit iCloud iOS Development Data Sync