/cloudkit
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
$ npx -y skills add dpearson2699/swift-ios-skills --skill cloudkit --agent claude-codeHow it fires
How this skill gets triggered: by you, by Claude, or both.
- Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
- You can call itInvoke it directly when you want it.
- Slash command
/cloudkit
Context preview
The summary Claude sees to decide when to auto-load this skill.
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
SKILL.md
cloudkit.SKILL.mdname: cloudkit
description: "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."
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.
Contents
- [Container and Database Setup](#container-and-database-setup)
- [Workflow](#workflow)
- [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)
Workflow
1. Choose the database scope and sync owner; verify capability, container, account status, schema, and environment before writing records. 2. Make a local change durable, enqueue it, then let subscriptions or `CKSyncEngine` drive remote work rather than polling. 3. Persist change tokens or sync-engine state after successful application. 4. Test offline edits, partial failure, rate limiting, token expiry, conflict, account loss, zone deletion, and relaunch. 5. On failure, classify the `CKError`, restore the affected fixture or queue item, apply the documented retry/reset/merge action, and rerun the same scenario. Never restart a full sync blindly after partial success.
Load [references/cloudkit-patterns.md](references/cloudkit-patterns.md) for incremental zone changes, shares, assets, batch operations, and Dashboard procedures.
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.
// Q
Read more
name: cloudkit description: "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."
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.
Contents
- [Container and Database Setup](#container-and-database-setup)
- [Workflow](#workflow)
- [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)
Workflow
1. Choose the database scope and sync owner; verify capability, container, account status, schema, and environment before writing records. 2. Make a local change durable, enqueue it, then let subscriptions or `CKSyncEngine` drive remote work rather than polling. 3. Persist change tokens or sync-engine state after successful application. 4. Test offline edits, partial failure, rate limiting, token expiry, conflict, account loss, zone deletion, and relaunch. 5. On failure, classify the `CKError`, restore the affected fixture or queue item, apply the documented retry/reset/merge action, and rerun the same scenario. Never restart a full sync blindly after partial success.
Load [references/cloudkit-patterns.md](references/cloudkit-patterns.md) for incremental zone changes, shares, assets, batch operations, and Dashboard procedures.
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.
// Q
86 agent skills optimized for iOS 26+ development with Swift 6.3 and modern Apple frameworks.
Repo: dpearson2699/swift-ios-skills
Other skills on swift-ios-skills.
- /accessorysetupkit
Discover and configure Bluetooth and Wi-Fi accessories using AccessorySetupKit. Use when presenting a privacy-preserving accessory picker, defining discovery descriptors for BLE or Wi-Fi devices, handling accessory session events, migrating from CoreBluetooth permission-based
Open skill - /activitykit
Implement, review, or improve Live Activities and Dynamic Island experiences in iOS apps using ActivityKit. Use when building real-time updating widgets for the Lock Screen and Dynamic Island — delivery tracking, sports scores, ride-sharing status, workout timers, media
Open skill - /adattributionkit
Measure ad effectiveness with privacy-preserving attribution using AdAttributionKit. Use when registering ad impressions, handling attribution postbacks, updating conversion values, implementing re-engagement attribution, configuring publisher or advertiser apps, or replacing
Open skill - /alarmkit
Implement AlarmKit alarms and countdown timers for iOS and iPadOS with Lock Screen, Dynamic Island, StandBy, and paired Apple Watch system UI. Covers AlarmManager scheduling, AlarmAttributes and AlarmPresentation, system Stop and AlarmButton secondary actions, authorization,
Open skill - /app-clips
Build iOS App Clips with invocation URLs, App Clip Codes, NFC, QR codes, Safari banners, Maps, Messages, target setup, App Store Connect experiences, size/capability constraints, NSUserActivity routing, SKOverlay promotion, App Group/keychain handoff, ephemeral notifications,
Open skill - /app-intents
Implement App Intents for Siri, Shortcuts, Spotlight, widgets, Control Center, and Apple Intelligence on iOS. Covers AppIntent actions, AppEntity and EntityQuery models, AppShortcutsProvider phrases, IndexedEntity Spotlight indexing, WidgetConfigurationIntent, SnippetIntent, and
Open skill

