Claude
Skills
Sign in
Back

cloudkit

Included with Lifetime
$97 forever

Implement, review, or improve CloudKit and iCloud sync in iOS/macOS apps. Use when working with CKContainer, CKRecord, CKQuery, CKSubscription, CKSyncEngine, CKShare, NSUbiquitousKeyValueStore, or iCloud Drive file coordination; when syncing SwiftData models via ModelConfiguration with cloudKitDatabase; when handling CKError codes for conflict resolution, network failures, or quota limits; or when checking iCloud account status before performing sync operations.

Code Review

What this skill does


# 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](#container-and-database-setup)
- [CKRecord CRUD](#ckrecord-crud)
- [CKQuery](#ckquery)
- [CKSubscription](#cksubscription)
- [CKSyncEngine (iOS 17+)](#cksyncengine-ios-17)
- [SwiftData + CloudKit](#swiftdata--cloudkit)
- [NSUbiquitousKeyValueStore](#nsubiquitouskeyvaluestore)
- [iCloud Drive File Sync](#icloud-drive-file-sync)
- [Account Status and Error Handling](#account-status-and-error-handling)
- [Conflict Resolution](#conflict-resolution)
- [Common Mistakes](#common-mistakes)
- [Review Checklist](#review-checklist)
- [References](#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 |

```swift
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).

```swift
// 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.

```swift
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.

```swift
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.

```swift
// 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:

```swift
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.

```swift
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) }
   
Files: 3
Size: 36.9 KB
Complexity: 47/100
Category: Code Review

Related in Code Review