How do I sync data between devices with CloudKit in Swift?

Syncing data between devices using CloudKit in Swift involves leveraging the CloudKit framework to manage user data in a secure and scalable manner. You can easily save, retrieve, and update data across all devices logged into the same iCloud account.

Here's an example of how to save and fetch data using CloudKit:

// Import CloudKit framework import CloudKit // Create a CloudKit container let container = CKContainer.default() // Create a public database let publicDatabase = container.publicCloudDatabase // Function to save data func saveData(recordName: String, data: String) { let record = CKRecord(recordType: "ExampleType") record["data"] = data as CKRecordValue publicDatabase.save(record) { (record, error) in if let error = error { print("Error saving record: \(error.localizedDescription)") } else { print("Record saved successfully!") } } } // Function to fetch data func fetchData() { let query = CKQuery(recordType: "ExampleType", predicate: NSPredicate(value: true)) publicDatabase.perform(query, inZoneWith: nil) { (results, error) in if let error = error { print("Error fetching records: \(error.localizedDescription)") } else { if let records = results { for record in records { if let data = record["data"] as? String { print("Fetched data: \(data)") } } } } } } // Example usage saveData(recordName: "example1", data: "Hello, World!") fetchData()

CloudKit Swift sync data iCloud Apple development mobile app development