mcpField
C
cloudkit-sync

cloudkit-sync

github.com/dpearson2699云与 DevOps1.2k413 次安装13 周前更新
代码仓库

关于 cloudkit-sync

面向 Swift 开发者的 CloudKit 与 iCloud 同步参考技能,涵盖记录、文件及 SwiftData 同步,并提供冲突处理和错误恢复指导。

主要功能

  1. 01CloudKit 记录增删改查与查询
  2. 02订阅和推送同步
  3. 03CKSyncEngine 集成
  4. 04SwiftData 与 CloudKit 集成
  5. 05iCloud 键值及文件同步
  6. 06冲突解决与错误处理

适用场景

  1. 01为应用配置 CloudKit 容器和数据库
  2. 02实现跨设备记录和文件同步
  3. 03处理离线、重试及账户状态
  4. 04设计 CloudKit 冲突合并逻辑

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/dpearson2699/swift-ios-skills --skill cloudkit-sync

安装后在 Claude Code 中输入/cloudkit-sync确认已加载。

附带文件references/cloudkit-patterns.md

详细介绍

CloudKit 和 iCloud 同步

使用 CloudKit、iCloud 键值存储和 iCloud Drive 在设备间同步数据。涵盖容器设置、记录的增删改查、查询、订阅、CKSyncEngine、SwiftData 集成、冲突解决和错误处理。面向 iOS 26+ 和 Swift 6.2;相关内容会注明较早版本的适用情况。

目录

容器和数据库设置

在 Signing & Capabilities 中启用 iCloud + CloudKit。一个容器提供三个数据库:

数据库范围是否需要 iCloud存储配额
Public所有用户读取:否,写入:是App 配额
Private当前用户是用户配额
Shared共享记录是所有者配额
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 增删改查

记录是键值对。每条记录最大为 1 MB(不包括 CKAsset 数据)。

// 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)
自定义记录区域(仅限 Private/Shared)

自定义区域支持原子提交、变更跟踪和共享。

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

使用 NSPredicate 查询记录。支持:==、!=、<、>、<=、>=、 BEGINSWITH、CONTAINS、IN、AND、NOT、BETWEEN、 distanceToLocation:fromLocation:。

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

记录在服务端发生变更时,订阅会触发推送通知。 CloudKit 会自动启用 APNs——无需显式配置推送权限。

// 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)

在 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 是推荐的同步方式。它会自动处理调度、瞬时错误重试、变更令牌和推送通知。 仅适用于 private 和 shared 数据库。

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) {
        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
    ) -> CKSyncEngine.RecordZoneChangeBatch? {
        let pending = syncEngine.state.pendingRecordZoneChanges
        return CKSyncEngine.RecordZoneChangeBatch(
            pendingChanges: Array(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()

要点:在多次启动之间持久化 stateSerialization;引擎需要它才能从正确的变更令牌恢复。

SwiftData + CloudKit

ModelConfiguration 支持 CloudKit 同步。CloudKit 模型必须使用可选属性,并避免使用唯一约束。

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)

CloudKit 模型规则:所有非 String 属性都使用可选类型;避免使用 #Unique;保持模型扁平;对大型数据使用 @Attribute(.externalStorage);避免复杂的关系图。

NSUbiquitousKeyValueStore

简单的键值同步。最多 1024 个键,总计 1 MB,每个值最大 1 MB。iCloud 不可用时会在本地存储。

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 文件同步

使用 FileManager ubiquity API 进行文档级同步。

guard let ubiquityURL = FileManager.default.url(
    forUbiquityContainerIdentifier: "iCloud.com.example.app"
) else { return }  // iCloud not available

let docsURL = ubiquityURL.appendingPathComponent("Documents")
let cloudURL = docsURL.appendingPathComponent("report.pdf")
try FileManager.default.setUbiquitous(true, itemAt: localURL, destinationURL: cloudURL)

// Monitor iCloud files
let query = NSMetadataQuery()
query.predicate = NSPredicate(format: "%K LIKE '*.pdf'", NSMetadataItemFSNameKey)
query.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
NotificationCenter.default.addObserver(
    forName: .NSMetadataQueryDidFinishGathering, object: query, queue: .main
) { _ in
    query.disableUpdates()
    for item in query.results as? [NSMetadataItem] ?? [] {
        let name = item.value(forAttribute: NSMetadataItemFSNameKey) as? String
        let status = item.value(
            forAttribute: NSMetadataUbiquitousItemDownloadingStatusKey) as? String
    }
    query.enableUpdates()
}
query.start()

账户状态和错误处理

同步前务必检查账户状态。监听 .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 处理
错误代码策略
.networkFailure、.networkUnavailable网络恢复后排队重试
.serverRecordChanged执行三方合并(参见“冲突解决”)
.requestRateLimited、.zoneBusy、.serviceUnavailable在 retryAfterSeconds 指定的时间后重试
.quotaExceeded通知用户;减少数据用量
.notAuthenticated提示用户登录 iCloud
.partialFailure按项检查 partialErrorsByItemID
.changeTokenExpired重置令牌,重新获取所有变更
.userDeletedZone重新创建区域并重新上传数据
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)
    }
}

冲突解决

保存已在服务端发生变更的记录时,CloudKit 会通过 .serverRecordChanged 返回三个版本的记录。务必将变更合并到 serverRecord 中——它具有正确的变更标签。

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) }
}

常见错误

不要: 未检查账户状态就执行同步操作。 应该: 先检查 CKContainer.accountStatus();处理 .noAccount。

// WRONG
try await privateDB.save(record)
// CORRECT
guard try await CKContainer.default().accountStatus() == .available
else { throw SyncError.noiCloudAccount }
try await privateDB.save(record)

不要: 忽略 .serverRecordChanged 错误。 应该: 使用祖先、客户端和服务端记录实现三方合并。

不要: 将用户专属数据存储在公共数据库中。 应该: 个人数据使用私有数据库;公共数据库仅用于全应用共享的内容。

不要: 以为保存后数据会立即可用。 应该: 乐观地更新本地缓存,并在获取数据时进行协调。

不要: 定时轮询更改。 应该: 使用 CKDatabaseSubscription 或 CKSyncEngine 实现基于推送的同步。

// 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)

不要: 遇到速率限制时立即重试。 应该: 使用 CKError.retryAfterSeconds 等待所需时长。

不要: 将冲突更改合并到 clientRecord。 应该: 始终合并到 serverRecord 中——它具有正确的更改标记。

不要: 每次获取数据时都传入 nil 更改令牌。 应该: 将更改令牌持久化到磁盘,并在后续获取时提供。

审查清单

  • 在 Signing & Capabilities 中启用了 iCloud + CloudKit 功能
  • 同步前检查账户状态;妥善处理 .noAccount
  • 用户数据使用私有数据库;公共数据库仅用于共享内容
  • 使用三方合并将 CKError.serverRecordChanged 合并到 serverRecord
  • 将网络故障排队以便重试;遵循 retryAfterSeconds
  • 使用 CKDatabaseSubscription 或 CKSyncEngine 实现基于推送的同步
  • 将更改令牌持久化到磁盘;changeTokenExpired 时重置并重新获取
  • 通过 partialErrorsByItemID 检查每项的 .partialFailure 错误
  • 通过重新创建区域并重新同步来处理 .userDeletedZone
  • SwiftData CloudKit 模型使用可选项,不使用 #Unique,大数据使用 .externalStorage
  • 监听 NSUbiquitousKeyValueStore.didChangeExternallyNotification
  • 敏感数据在 CKRecord 上使用 encryptedValues(而非普通字段)
  • 在各次启动之间持久化 CKSyncEngine 状态序列化数据(iOS 17+)

参考资料

评论

支持 Markdown