mcpField
C
cloudkit-sync

cloudkit-sync

github.com/dpearson2699クラウド・DevOps1.2k413 回インストール13 週間前に更新
リポジトリ

cloudkit-sync について

CloudKit と iCloud 同期を実装する Swift 開発者向けのリファレンススキルです。レコード、ファイル、SwiftData の同期に加え、競合解決とエラー処理を扱います。

主な機能

  1. 01CloudKit のレコード CRUD とクエリ
  2. 02サブスクリプションとプッシュ同期
  3. 03CKSyncEngine の統合
  4. 04SwiftData と CloudKit の連携
  5. 05iCloud のキー値・ファイル同期
  6. 06競合解決とエラー処理

活用シーン

  1. 01CloudKit コンテナとデータベースの設定
  2. 02デバイス間のレコード・ファイル同期の実装
  3. 03オフライン、再試行、アカウント状態への対応
  4. 04CloudKit の競合マージ設計

インストール

コマンドをコピーしてターミナルで実行します。

$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 を使用して、デバイス間でデータを同期します。コンテナの設定、レコードの CRUD、クエリ、サブスクリプション、CKSyncEngine、SwiftData との統合、競合解決、エラー処理について説明します。iOS 26 以降、Swift 6.2 を対象としています。関連する箇所では、それ以前のバージョンでの利用可否についても記載しています。

目次

コンテナとデータベースの設定

「Signing & Capabilities」で iCloud + CloudKit を有効にします。コンテナには、次の 3 つのデータベースがあります。

データベース範囲iCloud が必要ストレージの割り当て
パブリックすべてのユーザー読み取り:不要、書き込み:必要アプリの割り当て
プライベート現在のユーザー必要ユーザーの割り当て
共有共有レコード必要オーナーの割り当て
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

レコードはキーと値のペアです。1 レコードあたりの最大サイズは 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)
カスタムレコードゾーン(プライベート/共有のみ)

カスタムゾーンは、アトミックなコミット、変更の追跡、共有に対応しています。

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 は、推奨される同期方法です。スケジュール設定、一時的なエラーの再試行、変更トークン、プッシュ通知を自動的に処理します。 プライベートデータベースと共有データベースのみで動作します。

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、.serviceUnavailableretryAfterSeconds の後に再試行する
.quotaExceededユーザーに通知し、データ使用量を減らす
.notAuthenticatediCloud へのサインインを促す
.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 は 3 つのレコードバージョンを含む .serverRecordChanged を返します。必ず serverRecord にマージしてください。正しい変更タグが設定されているのは 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 時にリセットして再フェッチしている
  • .partialFailure エラーを partialErrorsByItemID でアイテムごとに確認している
  • .userDeletedZone を処理し、ゾーンを再作成して再同期している
  • SwiftData の CloudKit モデルでオプショナルを使用し、#Unique を使わず、大きなデータには .externalStorage を使用している
  • NSUbiquitousKeyValueStore.didChangeExternallyNotification を監視している
  • 機密データには CKRecord の encryptedValues を使用している(通常のフィールドは使用しない)
  • CKSyncEngine の状態シリアル化を起動間で保持している(iOS 17 以降)

参考資料

コメント