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()
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?