Implement, review, or improve CloudKit and iCloud sync in iOS/macOS apps. Use when working with CKContainer, CKRecord, CKQuery, CKSubscription, CKSyncEngine,…
CloudKit
Sync data across devices using CloudKit, iCloud key-value storage, and iCloud
Drive. Covers container setup, record CRUD, queries, subscriptions, CKSyncEngine,
SwiftData integration, conflict resolution, and error handling. Targets iOS 26+
with Swift 6.3; older availability noted where relevant.
Contents
Container and Database Setup
CKRecord CRUD
CKQuery
CKSubscription
CKSyncEngine (iOS 17+)
SwiftData + CloudKit
NSUbiquitousKeyValueStore
iCloud Drive File Sync
Account Status and Error Handling
Conflict Resolution
Common Mistakes
Review Checklist
References
Container and Database Setup
Enable iCloud + CloudKit in Signing & Capabilities. A container provides three databases:
Database
Scope
Requires iCloud
Storage Quota
Public
All users
Read: No, Write: Yes
App quota
Private
Current user
Yes
User quota
Shared
Shared records
Yes
Owner quota
import CloudKit
let container = CKContainer.default()
// Or named: CKContainer(identifier: "iCloud.com.example.app")
let publicDB = container.publicCloudDatabase
let privateDB = container.privateCloudDatabase
let sharedDB = container.sharedCloudDatabase
CKRecord CRUD
Records are key-value pairs. Max 1 MB per record (excluding CKAsset data).
// CREATE
let record = CKRecord(recordType: "Note")
record["title"] = "Meeting Notes" as CKRecordValue
record["body"] = "Discussed Q3 roadmap" as CKRecordValue
record["createdAt"] = Date() as CKRecordValue
record["tags"] = ["work", "planning"] as CKRecordValue
let saved = try await privateDB.save(record)
// FETCH by ID
let recordID = CKRecord.ID(recordName: "unique-id-123")
let fetched = try await privateDB.record(for: recordID)
// UPDATE -- fetch first, modify, then save
fetched["title"] = "Updated Title" as CKRecordValue
let updated = try await privateDB.save(fetched)
// DELETE
try await privateDB.deleteRecord(withID: recordID)
Custom Record Zones
Apps create custom zones in the private database. Shared databases expose zones
that other users share with the current user. Custom zones support atomic
commits, change tracking, and sharing; public databases do not support custom
zones.
let zoneID = CKRecordZone.ID(zoneName: "NotesZone")
let zone = CKRecordZone(zoneID: zoneID)
try await privateDB.save(zone)
let recordID = CKRecord.ID(recordName: UUID().uuidString, zoneID: zoneID)
let record = CKRecord(recordType: "Note", recordID: recordID)
CKQuery
Query records with NSPredicate. Supported: ==, !=, <, >, <=, >=,
BEGINSWITH, CONTAINS, IN, AND, NOT, BETWEEN,
distanceToLocation:fromLocation:.
CONTAINS tests list membership except for tokenized full-text search with
self CONTAINS. BEGINSWITH is the string-prefix operator; unsupported
operators, key paths, or field types fail when the query executes.
For every encryption review, explicitly call out field eligibility: encrypted
values cannot be queried or sorted; CKAsset is encrypted by default; and
CKRecord.Reference cannot be encrypted because CloudKit needs it server-side.
let predicate = NSPredicate(format: "title BEGINSWITH %@", "Meeting")
let query = CKQuery(recordType: "Note", predicate: predicate)
query.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: false)]
let (results, _) = try await privateDB.records(matching: query)
for (_, result) in results {
let record = try result.get()
print(record["title"] as? String ?? "")
}
// Fetch all records of a type
let allQuery = CKQuery(recordType: "Note", predicate: NSPredicate(value: true))
// Full-text search across string fields
let searchQuery = CKQuery(
recordType: "Note",
predicate: NSPredicate(format: "self CONTAINS %@", "roadmap")
)
// Compound predicate
let compound = NSCompoundPredicate(andPredicateWithSubpredicates: [
NSPredicate(format: "createdAt > %@", cutoffDate as NSDate),
NSPredicate(format: "tags CONTAINS %@", "work")
])
CKSubscription
Subscriptions trigger push notifications when records change server-side.
CloudKit/Xcode handles the APNs entitlement when CloudKit is enabled; no
separate explicit App ID push setup is needed. Silent/background processing
still needs Background Modes > Remote notifications.
// Query subscription -- fires when matching records change
let subscription = CKQuerySubscription(
recordType: "Note",
predicate: NSPredicate(format: "tags CONTAINS %@", "urgent"),
subscriptionID: "urgent-notes",
options: [.firesOnRecordCreation, .firesOnRecordUpdate]
)
let notifInfo = CKSubscription.NotificationInfo()
notifInfo.shouldSendContentAvailable = true // silent push
subscription.notificationInfo = notifInfo
try await privateDB.save(subscription)
// Database subscription -- fires on any database change
let dbSub = CKDatabaseSubscription(subscriptionID: "private-db-changes")
dbSub.notificationInfo = notifInfo
try await privateDB.save(dbSub)
// Record zone subscription -- fires on changes within a zone
let zoneSub = CKRecordZoneSubscription(
zoneID: CKRecordZone.ID(zoneName: "NotesZone"),
subscriptionID: "notes-zone-changes"
)
zoneSub.notificationInfo = notifInfo
try await privateDB.save(zoneSub)
Handle in AppDelegate:
func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any]
) async -> UIBackgroundFetchResult {
let notification = CKNotification(fromRemoteNotificationDictionary: userInfo)
guard notification?.subscriptionID == "private-db-changes" else { return .noData }
// Fetch changes using CKSyncEngine or CKFetchRecordZoneChangesOperation
return .newData
}
CKSyncEngine (iOS 17+)
CKSyncEngine is the recommended sync approach for custom model data. It
handles scheduling, transient retries, change tokens, and database
subscriptions, but not app-specific save failures: CKError.serverRecordChanged
from sentRecordZoneChanges.failedRecordSaves still requires custom conflict
resolution and rescheduling. Automatic sync timing is indeterminate. Requires
CloudKit capability + Remote notifications; private/shared databases only.
import CloudKit
final class SyncManager: CKSyncEngineDelegate {
let syncEngine: CKSyncEngine
init(container: CKContainer = .default()) {
let config = CKSyncEngine.Configuration(
database: container.privateCloudDatabase,
stateSerialization: Self.loadState(),
delegate: self
)
self.syncEngine = CKSyncEngine(config)
}
func handleEvent(_ event: CKSyncEngine.Event, syncEngine: CKSyncEngine) async {
switch event {
case .stateUpdate(let update):
Self.saveState(update.stateSerialization)
case .accountChange(let change):
handleAccountChange(change)
case .fetchedRecordZoneChanges(let changes):
for mod in changes.modifications { processRemoteRecord(mod.record) }
for del in changes.deletions { processRemoteDeletion(del.recordID) }
case .sentRecordZoneChanges(let sent):
for saved in sent.savedRecords { markSynced(saved) }
for fail in sent.failedRecordSaves { handleSaveFailure(fail) }
default: break
}
}
func nextRecordZoneChangeBatch(
_ context: CKSyncEngine.SendChangesContext,
syncEngine: CKSyncEngine
) async -> CKSyncEngine.RecordZoneChangeBatch? {
let pending = syncEngine.state.pendingRecordZoneChanges
.filter { context.options.zoneIDs.contains($0) }
return await CKSyncEngine.RecordZoneChangeBatch(
pendingChanges: pending
) { recordID in self.recordToSend(for: recordID) }
}
}
// Schedule changes
let zoneID = CKRecordZone.ID(zoneName: "NotesZone")
let recordID = CKRecord.ID(recordName: noteID, zoneID: zoneID)
syncEngine.state.add(pendingRecordZoneChanges: [.saveRecord(recordID)])
// Trigger immediate sync (pull-to-refresh)
try await syncEngine.fetchChanges()
try await syncEngine.sendChanges()
Key point: persist stateSerialization across launches; the engine needs it
to resume from the correct change token.
SwiftData + CloudKit
ModelConfiguration supports CloudKit sync. In every SwiftData CloudKit
implementation or review, always report two verdicts:
Model compatibility: no #Unique or unique constraints, optional
relationships, no .deny, and external storage for large Data.
Schema rollout: initialize the development schema in nonproduction builds,
verify it in CloudKit Dashboard, promote it before release, and after
production promotion only add schema; don't delete model types or change
existing attributes.
import SwiftData
@Model
class Note {
var title: String
var body: String?
var createdAt: Date?
@Attribute(.externalStorage) var imageData: Data?
init(title: String, body: String? = nil) {
self.title = title
self.body = body
self.createdAt = Date()
}
}
let config = ModelConfiguration(
"Notes",
cloudKitDatabase: .private("iCloud.com.example.app")
)
let container = try ModelContainer(for: Note.self, configurations: config)
NSUbiquitousKeyValueStore
Simple key-value sync. Max 1024 keys, 1 MB total, 1 MB per value. Stores
locally when iCloud is unavailable.
let kvStore = NSUbiquitousKeyValueStore.default
// Write
kvStore.set("dark", forKey: "theme")
kvStore.set(14.0, forKey: "fontSize")
kvStore.set(true, forKey: "notificationsEnabled")
kvStore.synchronize()
// Read
let theme = kvStore.string(forKey: "theme") ?? "system"
// Observe external changes
NotificationCenter.default.addObserver(
forName: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
object: kvStore, queue: .main
) { notification in
guard let userInfo = notification.userInfo,
let reason = userInfo[NSUbiquitousKeyValueStoreChangeReasonKey] as? Int,
let keys = userInfo[NSUbiquitousKeyValueStoreChangedKeysKey] as? [String]
else { return }
switch reason {
case NSUbiquitousKeyValueStoreServerChange:
for key in keys { applyRemoteChange(key: key) }
case NSUbiquitousKeyValueStoreInitialSyncChange:
reloadAllSettings()
case NSUbiquitousKeyValueStoreQuotaViolationChange:
handleQuotaExceeded()
default: break
}
}
iCloud Drive File Sync
Use FileManager ubiquity APIs for document-level sync. Call
url(forUbiquityContainerIdentifier:) and setUbiquitous off the main thread;
setUbiquitous performs coordinated file work and can block. If the app is
presenting the file, configure an active file presenter before moving it.
Task.detached {
guard let ubiquityURL = FileManager.default.url(
forUbiquityContainerIdentifier: "iCloud.com.example.app"
) else { return } // iCloud not available
let docsURL = ubiquityURL.appendingPathComponent("Documents")
try FileManager.default.createDirectory(at: docsURL, withIntermediateDirectories: true)
let cloudURL = docsURL.appendingPathComponent("report.pdf")
try FileManager.default.setUbiquitous(true, itemAt: localURL, destinationURL: cloudURL)
}
Monitor files with NSMetadataQuery scoped to
NSMetadataQueryUbiquitousDocumentsScope or
NSMetadataQueryUbiquitousDataScope.
Account Status and Error Handling
Always check account status before sync. Listen for .CKAccountChanged.
func checkiCloudStatus() async throws -> CKAccountStatus {
let status = try await CKContainer.default().accountStatus()
switch status {
case .available: return status
case .noAccount: throw SyncError.noiCloudAccount
case .restricted: throw SyncError.restricted
case .temporarilyUnavailable: throw SyncError.temporarilyUnavailable
case .couldNotDetermine: throw SyncError.unknown
@unknown default: throw SyncError.unknown
}
}
CKError Handling
Error Code
Strategy
.networkFailure, .networkUnavailable
Queue for retry when network returns
.serverRecordChanged
Three-way merge (see Conflict Resolution)
.requestRateLimited, .zoneBusy, .serviceUnavailable
Retry after retryAfterSeconds
.quotaExceeded
Notify user; reduce data usage
.notAuthenticated
Prompt iCloud sign-in
.partialFailure
Inspect partialErrorsByItemID per item
.changeTokenExpired
Reset token, refetch all changes
.userDeletedZone
Recreate zone and re-upload data
func handleCloudKitError(_ error: Error) {
guard let ckError = error as? CKError else { return }
switch ckError.code {
case .networkFailure, .networkUnavailable:
scheduleRetryWhenOnline()
case .serverRecordChanged:
resolveConflict(ckError)
case .requestRateLimited, .zoneBusy, .serviceUnavailable:
let delay = ckError.retryAfterSeconds ?? 3.0
scheduleRetry(after: delay)
case .quotaExceeded:
notifyUserStorageFull()
case .partialFailure:
if let partial = ckError.partialErrorsByItemID {
for (_, itemError) in partial { handleCloudKitError(itemError) }
}
case .changeTokenExpired:
resetChangeToken()
case .userDeletedZone:
recreateZoneAndResync()
default: logError(ckError)
}
}
Conflict Resolution
When saving a record that changed server-side, CloudKit returns
.serverRecordChanged with three record versions. Always merge into
serverRecord -- it has the correct change tag.
func resolveConflict(_ error: CKError) {
guard error.code == .serverRecordChanged,
let ancestor = error.ancestorRecord,
let client = error.clientRecord,
let server = error.serverRecord
else { return }
// Merge client changes into server record
for key in client.changedKeys() {
if server[key] == ancestor[key] {
server[key] = client[key] // Server unchanged, use client
} else if client[key] == ancestor[key] {
// Client unchanged, keep server (already there)
} else {
server[key] = mergeValues( // Both changed, custom merge
ancestor: ancestor[key], client: client[key], server: server[key])
}
}
Task { try await CKContainer.default().privateCloudDatabase.save(server) }
}
Common Mistakes
DON'T: Perform sync operations without checking account status.
DO: Check CKContainer.accountStatus() first; handle .noAccount.
// WRONG
try await privateDB.save(record)
// CORRECT
guard try await CKContainer.default().accountStatus() == .available
else { throw SyncError.noiCloudAccount }
try await privateDB.save(record)
DON'T: Ignore .serverRecordChanged errors.
DO: Implement three-way merge using ancestor, client, and server records.
DON'T: Store user-specific data in the public database.
DO: Use private database for personal data; public only for app-wide content.
DON'T: Poll for changes on a timer.
DO: Use CKDatabaseSubscription or CKSyncEngine for push-based sync.
// WRONG
Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { _ in fetchAll() }
// CORRECT
let sub = CKDatabaseSubscription(subscriptionID: "db-changes")
sub.notificationInfo = CKSubscription.NotificationInfo()
sub.notificationInfo?.shouldSendContentAvailable = true
try await privateDB.save(sub)
DON'T: Retry immediately on rate limiting.
DO: Use CKError.retryAfterSeconds to wait the required duration.
DON'T: Assume CKSyncEngine handles .serverRecordChanged conflicts for you.
DO: Resolve failedRecordSaves with a three-way merge, then reschedule the save.
DON'T: Pass nil change token on every fetch.
DO: Persist change tokens to disk and supply them on subsequent fetches.
Review Checklist
iCloud + CloudKit capability enabled in Signing & Capabilities
Account status checked before sync; .noAccount handled gracefully
Private database used for user data; public only for shared content
Custom record zones created in private DB; shared DB zones discovered from shares
CKError.serverRecordChanged handled with three-way merge into serverRecord
Network failures queued for retry; retryAfterSeconds respected
CKDatabaseSubscription or CKSyncEngine used for push-based sync; Remote notifications enabled for background delivery
Change tokens persisted to disk; changeTokenExpired resets and refetches
.partialFailure errors inspected per-item via partialErrorsByItemID
.userDeletedZone handled by recreating zone and resyncing
SwiftData CloudKit review reports model compatibility and schema rollout: initialized/verified development schema, promoted before release, and additive-only production changes
NSUbiquitousKeyValueStore.didChangeExternallyNotification observed
Encryption review says CKRecord.Reference cannot use encryptedValues because CloudKit needs it server-side; no query/sort on encrypted fields; CKAsset is encrypted by default
CKSyncEngine state serialization persisted across launches (iOS 17+)
References
See references/cloudkit-patterns.md for incremental sync, CKShare, zones, CKAsset storage, batch operations, and Dashboard usage.
CloudKit Framework
CKContainer
CKRecord
CKQuery
CKSubscription
CKSyncEngine
CKShare
CKError
NSUbiquitousKeyValueStore
SwiftData CloudKit syncdon't have the plugin yet? install it then click "run inline in claude" again.
cloudkit syncs data across devices using CloudKit, iCloud key-value storage, and iCloud Drive. use this skill when implementing container setup, record CRUD, queries, subscriptions, CKSyncEngine, SwiftData integration, conflict resolution, and error handling in iOS 17+ with Swift 6.3 (older availability noted per feature).
cloudkit capability & entitlements
ckcontainer & databases
CKContainer.default() or named container CKContainer(identifier: "iCloud.com.example.app")network & account state
CKContainer.accountStatus() before any sync operation.CKAccountChanged notification for account changesremote notifications (cksyncengine & subscriptions)
UIApplication.registerForRemoteNotifications()persistent storage for sync state
external file sync (icloud drive)
"iCloud.com.example.app" (same as CloudKit container)cksyncengine delegate (ios 17+)
swiftdata + cloudkit
cloudKitDatabase: .private("iCloud.com.example.app")input: app identifier, desired database scope (public/private/shared)
steps:
let container = CKContainer.default() or named containeroutput: CKContainer instance with publicCloudDatabase, privateCloudDatabase, sharedCloudDatabase properties ready to use
input: zone name string, database reference
steps:
CKRecordZone.ID(zoneName: "NotesZone")CKRecordZone(zoneID: zoneID)database.save(zone).zoneBusy or .networkFailure queue for retryoutput: custom zone created in private or shared database; subsequent records can use this zone for atomic commits and change tracking
edge case: public database does not support custom zones; all public records go to default zone
input: record type (string), field key-value pairs, database reference
steps:
CKRecord(recordType: "Note")database.save(record)output: CKRecord with system-assigned recordID, change tag, and server timestamp
constraints: max 1 MB per record excluding CKAsset; CKAsset stored separately counts against storage quota
input: record ID (CKRecord.ID), database reference
steps:
CKRecord.ID(recordName: "unique-id-123") or CKRecord.ID(recordName: uuid, zoneID: zoneID)database.record(for: recordID).unknownItem error if record deleted server-sideoutput: CKRecord object with all fields populated; nil if not found (async throws)
input: fetched CKRecord, new field values, database reference
steps:
record["fieldName"] = newValue as CKRecordValuedatabase.save(record).serverRecordChanged, implement three-way merge (see decision points)output: CKRecord with updated change tag and server timestamp
critical: always fetch before updating; CloudKit uses change tag to detect conflicts
input: record ID, database reference
steps:
database.deleteRecord(withID: recordID).unknownItem if record already deleted.serverRecordChanged if concurrent delete occurred (rare)output: record removed from database; no return value on success
input: record type, NSPredicate, optional sort descriptors, database reference
steps:
NSPredicate(format: "title BEGINSWITH %@", "Meeting")CKQuery(recordType: "Note", predicate: predicate)query.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: false)]database.records(matching: query) returns tuple (results dict, cursor)output: dictionary of [CKRecord.ID: Result<CKRecord, Error>]; cursor for pagination
edge cases: empty result set returns empty dict (not an error); cursor nil means no more records; query fails entirely if unsupported operator or encrypted field used
input: record type, search term string, database reference
steps:
NSPredicate(format: "self CONTAINS %@", "roadmap")output: CKRecord objects matching any tokenized word in search term
input: multiple predicates, logical operators (AND/OR/NOT)
steps:
NSCompoundPredicate(andPredicateWithSubpredicates: [pred1, pred2])output: records matching all or any subpredicates per operator
input: record type, predicate, subscription ID, database reference, options (.firesOnRecordCreation, .firesOnRecordUpdate, .firesOnRecordDeletion)
steps:
CKQuerySubscription(recordType: "Note", predicate: NSPredicate(...), subscriptionID: "urgent-notes", options: [...])notifInfo.shouldSendContentAvailable = true (silent push)subscription.notificationInfo = notifInfodatabase.save(subscription)output: subscription persisted on server; CloudKit will send APNs when matching records change
constraints: private database subscriptions require user signed in to iCloud; public subscriptions trigger for any record match
input: subscription ID, database reference
steps:
CKDatabaseSubscription(subscriptionID: "private-db-changes")output: silent push sent on any record create/update/delete in that database
input: zone ID, subscription ID, database reference
steps:
CKRecordZoneSubscription(zoneID: zoneID, subscriptionID: "zone-changes")output: silent push sent on any change within the zone
input: remote notification userInfo dictionary
steps:
let notification = CKNotification(fromRemoteNotificationDictionary: userInfo)syncEngine.fetchChanges() or use CKFetchRecordZoneChangesOperationoutput: app syncs latest changes from CloudKit, updates local data model
edge case: notification may arrive while app is suspended; handle in background fetch or when app returns to foreground
input: CKContainer, state serialization from disk (if resuming), delegate instance
steps:
let state = try JSONDecoder().decode(...)CKSyncEngine.Configuration(database: container.privateCloudDatabase, stateSerialization: state, delegate: self)self.syncEngine = CKSyncEngine(config)output: CKSyncEngine ready to push/pull changes; engine will call delegate methods for events
critical: persist state serialization on every stateUpdate event; engine cannot resume correctly without it
input: record IDs to save or delete, syncEngine reference
steps:
syncEngine.state.add(pendingRecordZoneChanges: [.saveRecord(recordID)])syncEngine.fetchChanges() then syncEngine.sendChanges()output: pending changes queued in engine state; engine handles retry, rate limiting, and scheduling
input: CKSyncEngineDelegate protocol conformance
steps:
handleEvent(_ event:, syncEngine:) async to handle .stateUpdate, .accountChange, .fetchedRecordZoneChanges, .sentRecordZoneChangesnextRecordZoneChangeBatch(_:, syncEngine:) to supply pending local changes to sendoutput: engine calls delegate methods as sync events occur; app responds by updating UI and local storage
input: CKSyncEngine.SendChangesContext with failedRecordSaves, which include (recordID, error) pairs
steps:
.serverRecordChanged, extract ancestor, client, server records from errorsyncEngine.state.add(pendingRecordZoneChanges: [.saveRecord(mergedRecord.recordID)])output: conflict resolved; pending change rescheduled for send
input: Model class definition, data types (String, Int, Date, Optional, external storage for large Data)
steps:
@Attribute(.externalStorage) (e.g., imageData: Data?)ModelConfiguration("Notes", cloudKitDatabase: .private("iCloud.com.example.app"))try ModelContainer(for: Note.self, configurations: config)output: SwiftData model ready for CloudKit sync; schema will be mirrored to CloudKit
critical: initialize development schema in non-production builds first, verify it in CloudKit Dashboard, then promote to production; after production promotion, only add new models/fields (no deletions or attribute changes)
input: key string, value (String, Int, Double, Bool, Data)
steps:
let kvStore = NSUbiquitousKeyValueStore.defaultkvStore.set("dark", forKey: "theme")kvStore.synchronize()output: value synced to iCloud KV store; available on other devices signed in to same iCloud account
constraints: max 1024 keys, 1 MB total, 1 MB per value; app stores locally if iCloud unavailable
input: kvStore reference, observer setup
steps:
let theme = kvStore.string(forKey: "theme") ?? "system"output: app stays in sync with KV store changes from other devices
input: local file URL, ubiquity container identifier, optional file presenter (if file is open in app)
steps:
FileManager.default.url(forUbiquityContainerIdentifier: "iCloud.com.example.app")ubiquityURL.appendingPathComponent("Documents/report.pdf")FileManager.default.setUbiquitous(true, itemAt: localURL, destinationURL: cloudURL)output: file moved to iCloud Drive; syncs to other devices
edge case: setUbiquitous fails if destination already exists; check and delete or rename first
input: NSMetadataQuery, scope (UbiquitousDocumentsScope or UbiquitousDataScope)
steps:
NSMetadataQuery()query.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]query.predicate = NSPredicate(format: "kMDItemFSName like %@", "*.pdf")query.start()output: query updates as files sync to device; app can bind UI to results
input: CKContainer reference
steps:
CKContainer.default().accountStatus()output: verified account is in sync-ready state; exception thrown if not
critical: always check before sync; prevents cryptic downstream errors
input: CKError with code .networkFailure or .networkUnavailable
steps:
output: sync operation scheduled to retry; user informed of temporary unavailability
input: CKError with code .serverRecordChanged (contains ancestor, client, server records)
steps:
output: conflict resolved; server and client in agreement