Cloudkit

作者 dpearson26998d90fd121a26無授權條款1.1K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫2 個月前更新

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.

AI 產生的概覽

指導在 iOS 與 macOS 應用程式中實作、審查及除錯 CloudKit 與 iCloud 同步。

功能
提供 CloudKit 容器與資料庫設定、記錄新增修改刪除查詢、查詢、訂閱、CKSyncEngine、SwiftData 整合、NSUbiquitousKeyValueStore 以及 iCloud Drive 檔案協調的參考指引與程式碼範例。內容也涵蓋帳號狀態檢查、CKError 處理策略、三方衝突合併、常見錯誤與審查清單。隨附的參考檔案說明增量同步、共享、資源、批次操作與 Dashboard 操作流程。
適用情境
適用於在 Apple 平台應用程式中建置或審查 iCloud 同步時,例如使用 CKContainer、CKRecord、CKQuery、CKSubscription、CKSyncEngine、CKShare 或 NSUbiquitousKeyValueStore。也適合處理 CKError 錯誤碼、衝突解決、配額限制,或在同步前檢查 iCloud 帳號狀態。
執行需求
沒有指令碼,僅包含說明與參考文件。需要已啟用 iCloud 與 CloudKit 功能的 iOS 或 macOS 專案,以及用於設定容器與結構描述的 Apple 開發者帳號。

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

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 [blocked] 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:

DatabaseScopeRequires iCloudStorage Quota
PublicAll usersRead: No, Write: YesApp quota
PrivateCurrent userYesUser quota
SharedShared recordsYesOwner quota
swift
import CloudKit
let container = CKContainer.default()// Or named: CKContainer(identifier: "iCloud.com.example.app")
let publicDB  = container.publicCloudDatabaselet privateDB = container.privateCloudDatabaselet sharedDB  = container.sharedCloudDatabase

CKRecord CRUD

Records are key-value pairs. Max 1 MB per record (excluding CKAsset data).

swift
// CREATElet record = CKRecord(recordType: "Note")record["title"] = "Meeting Notes" as CKRecordValuerecord["body"] = "Discussed Q3 roadmap" as CKRecordValuerecord["createdAt"] = Date() as CKRecordValuerecord["tags"] = ["work", "planning"] as CKRecordValuelet saved = try await privateDB.save(record)
// FETCH by IDlet recordID = CKRecord.ID(recordName: "unique-id-123")let fetched = try await privateDB.record(for: recordID)
// UPDATE -- fetch first, modify, then savefetched["title"] = "Updated Title" as CKRecordValuelet updated = try await privateDB.save(fetched)
// DELETEtry 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 typelet allQuery = CKQuery(recordType: "Note", predicate: NSPredicate(value: true))
// Full-text search across string fieldslet searchQuery = CKQuery(    recordType: "Note",    predicate: NSPredicate(format: "self CONTAINS %@", "roadmap"))
// Compound predicatelet 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 changelet subscription = CKQuerySubscription(    recordType: "Note",    predicate: NSPredicate(format: "tags CONTAINS %@", "urgent"),    subscriptionID: "urgent-notes",    options: [.firesOnRecordCreation, .firesOnRecordUpdate])let notifInfo = CKSubscription.NotificationInfo()notifInfo.shouldSendContentAvailable = true  // silent pushsubscription.notificationInfo = notifInfotry await privateDB.save(subscription)
// Database subscription -- fires on any database changelet dbSub = CKDatabaseSubscription(subscriptionID: "private-db-changes")dbSub.notificationInfo = notifInfotry await privateDB.save(dbSub)
// Record zone subscription -- fires on changes within a zonelet zoneSub = CKRecordZoneSubscription(    zoneID: CKRecordZone.ID(zoneName: "NotesZone"),    subscriptionID: "notes-zone-changes")zoneSub.notificationInfo = notifInfotry 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) }        return await CKSyncEngine.RecordZoneChangeBatch(            pendingChanges: pending        ) { recordID in self.recordToSend(for: recordID) }    }}
// Schedule changeslet 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.
swift
import SwiftData
@Modelclass 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.

swift
let kvStore = NSUbiquitousKeyValueStore.default
// WritekvStore.set("dark", forKey: "theme")kvStore.set(14.0, forKey: "fontSize")kvStore.set(true, forKey: "notificationsEnabled")kvStore.synchronize()
// Readlet theme = kvStore.string(forKey: "theme") ?? "system"
// Observe external changesNotificationCenter.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.

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

swift
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 CodeStrategy
.networkFailure, .networkUnavailableQueue for retry when network returns
.serverRecordChangedThree-way merge (see Conflict Resolution)
.requestRateLimited, .zoneBusy, .serviceUnavailableRetry after retryAfterSeconds
.quotaExceededNotify user; reduce data usage
.notAuthenticatedPrompt iCloud sign-in
.partialFailureInspect partialErrorsByItemID per item
.changeTokenExpiredReset token, refetch all changes
.userDeletedZoneRecreate zone and re-upload data
swift
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.

swift
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

MistakeFix
Syncing without an account gateCheck accountStatus() and model .noAccount as a user-visible state.
Personal data in the public databaseUse private scope for user data; public scope is app-wide content.
Timer pollingUse database subscriptions or CKSyncEngine.
Immediate retry after throttlingRespect retryAfterSeconds and preserve pending work.
Assuming the engine resolves conflictsThree-way merge failedRecordSaves, then reschedule the save.
Starting every fetch with a nil tokenPersist tokens/state; reset only on the documented expiry path.

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

來源與署名

來源:dpearson2699/swift-ios-skills位於skills/cloudkit提交8d90fd1

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 dpearson2699/swift-ios-skills 的技能

Widgetkit

dpearson2699

指導實作、審查與改進 iOS、iPadOS、watchOS 與 CarPlay 上的 WidgetKit 小工具與控制項。

Software Development1.1K2 個月前更新

Weatherkit

dpearson2699

指導 iOS 開發者使用 WeatherService 取得 WeatherKit 預報、警報與署名資訊。

Software Development1.1K2 個月前更新

Vision Framework

dpearson2699

Implement computer vision features including text recognition (OCR), face detection, barcode scanning, image segmentation, object tracking, and document scanning in iOS apps. Covers both the modern Swift-native Vision API (iOS 18+) and legacy VNRequest patterns, VisionKit DataScannerViewController for live camera scanning, and CoreMLRequest/VNCoreMLRequest for custom model inference. Use when adding OCR, barcode scanning, face detection, or custom Core ML model inference with Vision.

待分類1.1K2 個月前更新

Tipkit

dpearson2699

Implement and review Apple TipKit feature-discovery UI for iOS 17+ apps. Use when adding or auditing in-app tips, contextual help, coach marks, Tip, TipView, popoverTip, rules, events, actions, display frequency, testing overrides, reusable tip identifiers, or iOS 18+ TipGroup and CloudKit tip sync; avoid for generic SwiftUI navigation or layout outside tip presentation.

待分類1.1K2 個月前更新

Tabletopkit

dpearson2699

指導使用 TabletopKit 在 visionOS 上打造多人空間桌遊,涵蓋棋具、座位、動作與 RealityKit 算繪。

Software Development1.1K2 個月前更新

Swiftui Webkit

dpearson2699

指導在 iOS 26 及更新版本的 SwiftUI App 中使用 WebKit for SwiftUI 嵌入與控制網頁內容。

Software Development1.1K2 個月前更新