SkillAtlasSkill 详情

cloudkit

86 agent skills optimized for iOS 26+ development with Swift 6.

审核状态:已审核Quality 72Security 78

复制安装命令

用 Codex 或 Claude 安装复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它先审查 Skill 页面再帮你安装。

复制前请先查看来源、License 和安全提示。

项目 README

来源文件:README.md

抓取于 2026年8月22日

Swift iOS Skills — Agent Skills for iOS 26+ & SwiftUI Development

GitHub stars Swift 6.3 Platform Claude Code OpenAI Codex Agent Skills tessl License: PolyForm Perimeter

86 agent skills optimized for iOS 26+ development with Swift 6.3 and modern Apple frameworks. All code examples, patterns, and guidance target the latest APIs -- Liquid Glass, approachable concurrency, Foundation Models, StoreKit 2, SwiftData, async/await URLSession, and more. No deprecated patterns.

Compatible with Claude Code, OpenAI Codex, Cursor, GitHub Copilot, and 40+ other agents. Follows the open Agent Skills standard.

Every skill is self-contained. No skill depends on another. Install only what you need.

Release history: CHANGELOG.md.

Contents

Install

Recommended: any agent via skills CLI

The skills CLI is the recommended install method.

Interactive install (recommended):

npx skills add dpearson2699/swift-ios-skills

Running the default command opens the skills CLI UI so you can choose which skills to install and which agent(s) to install them for.

Install everything for any coding agent:

npx skills add dpearson2699/swift-ios-skills --all

Use --all when you want the full set of 86 skills installed automatically for any coding agent.

Install specific skills directly:

npx skills add dpearson2699/swift-ios-skills --skill <skill-name> --skill <skill-name>

Check for updates to installed skills:

npx skills check

Update installed skills to the latest versions:

npx skills update

Use these after installing through the skills CLI.

Claude Code (via plugin marketplace)

Add the marketplace (one-time):

/plugin marketplace add dpearson2699/swift-ios-skills

Install everything:

/plugin install all-ios-skills@swift-ios-skills

Or install a themed bundle (bundles limit how many skills load into the context window — if you want everything, use all-ios-skills above instead of installing multiple bundles):

/plugin install swiftui-skills@swift-ios-skills
/plugin install swift-core-skills@swift-ios-skills
/plugin install ios-app-framework-skills@swift-ios-skills
/plugin install ios-data-framework-skills@swift-ios-skills
/plugin install ios-ai-ml-skills@swift-ios-skills
/plugin install ios-engineering-skills@swift-ios-skills
/plugin install ios-hardware-skills@swift-ios-skills
/plugin install ios-platform-skills@swift-ios-skills
/plugin install ios-gaming-skills@swift-ios-skills
/plugin install apple-kit-skills@swift-ios-skills

OpenAI Codex

$skill-installer install https://github.com/dpearson2699/swift-ios-skills/tree/main/skills/<skill-name>

Claude Web App / Claude Desktop

  1. Download the skill folder(s) you want from this repo
  2. Zip each skill folder
  3. Go to Settings > Capabilities and enable "Code execution and file creation"
  4. Go to Customize > Skills, click +, then Upload a skill
  5. Upload the zip

ChatGPT

  1. Download the skill folder(s) you want from this repo
  2. Zip each skill folder
  3. Click your profile icon in ChatGPT and select Skills
  4. Click New skill and select Upload from your computer
  5. Upload the zip

Plugin Bundles (Claude Code)

PluginSkills included
all-ios-skillsAll 86 skills
apple-kit-skills39 skills spanning Apple Kit frameworks plus CarPlay
swiftui-skillsfocus-engine, swiftui-animation, swiftui-gestures, swiftui-layout-components, swiftui-liquid-glass, swiftui-navigation, swiftui-patterns, swiftui-performance, swiftui-uikit-interop, swiftui-webkit
swift-core-skillscore-data, swift-api-design-guidelines, swift-architecture, swift-codable, swift-charts, swift-concurrency, swift-formatstyle, swift-language, swift-testing, swiftdata
ios-app-framework-skillsactivitykit, adattributionkit, alarmkit, app-clips, app-intents, avkit, carplay, mapkit, paperkit, pdfkit, photokit, push-notifications, storekit, tipkit, widgetkit
ios-data-framework-skillscloudkit, contacts-framework, eventkit, financekit, healthkit, musickit, passkit, weatherkit
ios-ai-ml-skillsapple-on-device-ai, coreml, natural-language, speech-recognition, vision-framework
ios-engineering-skillsapp-store-optimization, app-store-review, authentication, background-processing, cryptokit, debugging-instruments, device-integrity, ios-accessibility, ios-ettrace-performance, ios-localization, ios-memgraph-analysis, ios-networking, swift-security, swiftlint, ios-simulator, metrickit
ios-hardware-skillsaccessorysetupkit, core-bluetooth, core-motion, core-nfc, dockkit, pencilkit, realitykit, sensorkit
ios-platform-skillsappmigrationkit, audioaccessorykit, browserenginekit, callkit, cryptotokenkit, energykit, homekit, permissionkit, relevancekit, shareplay-activities
ios-gaming-skillsgamekit, scenekit, spritekit, tabletopkit

Skills

SwiftUI

SkillWhat it covers
focus-engine@FocusState, defaultFocus, focusSection, focused scene values, focus restoration, UIFocusGuide
swiftui-animationSpring animations, PhaseAnimator, KeyframeAnimator, matchedGeometryEffect, SF Symbols
swiftui-gesturesTap, drag, magnify, rotate, long press, simultaneous and sequential gestures
swiftui-layout-componentsGrid, LazyVGrid, Layout protocol, ViewThatFits, custom layouts
swiftui-liquid-glassiOS 26 Liquid Glass, glassEffect, GlassEffectContainer, morphing transitions
swiftui-navigationNavigationStack, NavigationSplitView, programmatic navigation, deep linking
swiftui-patterns@Observable, state ownership, environment wiring, view composition, async loading, MV-pattern architecture
swiftui-performanceRendering performance, view update optimization, layout thrash, Instruments profiling
swiftui-uikit-interopUIViewRepresentable, UIHostingController, Coordinator, incremental UIKit-to-SwiftUI migration
swiftui-webkitWebView, WebPage, navigation policies, JavaScript calls, local content, custom URL schemes

Core Swift

SkillWhat it covers
swift-api-design-guidelinesSwift API Design Guidelines -- argument labels, mutating/nonmutating pairs, documentation comments, naming conventions
swift-architectureArchitecture patterns: MV (@Observable), MVVM, MVI, TCA, Clean Architecture, Coordinator, decision framework
swift-codableSwift Codable, JSONDecoder, JSONEncoder, CodingKeys, custom decoding, nested JSON
swift-chartsBar, line, area, pie, donut, and 3D charts, scrolling, selection, annotations
swift-concurrencySwift 6.2 concurrency, Sendable, actors, structured concurrency, data-race safety
swift-formatstyleFormatStyle protocol, number/currency/date/duration/measurement formatting, custom styles
swift-languageSwift 6.3 language idioms, result builders, property wrappers, typed throws
swift-testingSwift Testing framework, @Test, @Suite, #expect, parameterized tests, mocking
core-dataCore Data persistence, NSPersistentContainer, NSFetchedResultsController, batch operations, staged migration
swiftdata@Model, @Query, #Predicate, ModelContainer, migrations, CloudKit sync, @ModelActor

App Experience Frameworks

SkillWhat it covers
activitykitActivityKit, Dynamic Island, Lock Screen Live Activities, push-to-update
adattributionkitPrivacy-preserving ad attribution, postbacks, conversion values, re-engagement
alarmkitAlarmKit system alarms and countdown timers, Lock Screen, Dynamic Island, Live Activities
app-clipsApp Clips, invocation URLs, NFC, QR, App Clip Codes, App Group handoff
app-intentsApp Intents for Siri, Shortcuts, Spotlight, widgets, and Apple Intelligence
avkitAVPlayerViewController, VideoPlayer, Picture-in-Picture, AirPlay, subtitles
carplayCarPlay templates, navigation, audio, communication, EV charging apps
mapkitMapKit, CoreLocation, annotations, geocoding, directions, geofencing
paperkitPaperMarkupViewController, markup editing, drawing, shapes (iOS 26)
pdfkitPDFView, PDFDocument, annotations, text search, form filling, thumbnails
photokitPhotosPicker, AVCaptureSession, photo library, video recording, media permissions
push-notificationsUNUserNotificationCenter, APNs, rich notifications, silent push, service extensions
storekitStoreKit 2 purchases, subscriptions, SubscriptionStoreView, transaction verification
tipkitFeature discovery tooltips, contextual tips, tip rules, tip events
widgetkitHome Screen, Lock Screen, and StandBy widgets, Control Center controls, timeline providers

Data & Service Frameworks

SkillWhat it covers
cloudkitCKContainer, CKRecord, subscriptions, sharing, CKSyncEngine, SwiftData sync
contacts-frameworkCNContactStore, fetch requests, key descriptors, CNContactPickerViewController, save requests
eventkitEKEventStore, EKEvent, EKReminder, recurrence rules, EventKitUI editors and choosers
financekitApple Card, Apple Cash, Wallet orders, transaction queries, account balances
healthkitHKHealthStore, queries, statistics, workout sessions, background delivery
musickitMusicKit authorization, catalog search, ApplicationMusicPlayer, MPRemoteCommandCenter
passkitApple Pay, PKPaymentRequest, PKPaymentAuthorizationController, Wallet passes
weatherkitWeatherService, current/hourly/daily forecasts, alerts, attribution requirements

AI & Machine Learning

SkillWhat it covers
apple-on-device-aiFoundation Models framework, Core ML, MLX Swift, on-device LLM inference
coremlCore ML model loading, prediction, MLTensor, compute unit configuration, VNCoreMLRequest, MLComputePlan
natural-languageNLTokenizer, NLTagger, sentiment analysis, language identification, embeddings, Translation
speech-recognitionSpeechAnalyzer, SpeechTranscriber, SFSpeechRecognizer, on-device recognition, audio buffer processing
vision-frameworkVision text recognition, face/barcode detection, image segmentation, VisionKit DataScannerViewController

iOS Engineering

SkillWhat it covers
app-store-optimizationASO keyword strategy, description writing, screenshot optimization, Custom Product Pages, A/B testing
app-store-reviewApp Review guidelines, rejection prevention, privacy manifests, ATT, HIG compliance
authenticationSign in with Apple, ASAuthorizationController, passkeys, biometric auth (LAContext), credential management
background-processingBGTaskScheduler, background refresh, URLSession background transfers
cryptokitSHA-2/SHA-3, HMAC, AES-GCM, ChaChaPoly, HPKE, ML-KEM/ML-DSA, P256/Curve25519 signing, ECDH, Secure Enclave
debugging-instrumentsXcode debugger, Instruments, os_signpost, MetricKit, crash symbolication
device-integrityDeviceCheck (DCDevice per-device bits), App Attest (DCAppAttestService attestation and assertion flows)
ios-accessibilityVoiceOver, Dynamic Type, custom rotors, accessibility focus, assistive-technology support
ios-ettrace-performanceETTrace launch/runtime capture, exact-build dSYM matching, processed flamegraph JSON, comparable verification
ios-localizationString Catalogs, pluralization, FormatStyle, right-to-left layout
ios-memgraph-analysisSimulator memgraph capture, leak ownership paths, reachable heap growth, raw evidence preservation
ios-networkingURLSession async/await, REST APIs, downloads/uploads, WebSockets, pagination, retry, caching
swift-securityKeychain Services, CryptoKit symmetric/asymmetric, biometric authentication, Secure Enclave, certificate trust, credential storage, OWASP compliance · Based on ivan-magda/swift-security-skill
ios-simulatorxcrun simctl commands, device lifecycle, push/location/privacy simulation, log streaming, simulator limitations
metrickitMetricManager async reports, hang/crash diagnostics, production performance telemetry
swiftlintSwiftLint setup, .swiftlint.yml, build tool plugin, rule selection, baselines, suppressions, CI integration

Hardware & Device Integration

SkillWhat it covers
accessorysetupkitPrivacy-preserving BLE/Wi-Fi accessory discovery, ASAccessorySession, picker UI
core-bluetoothCBCentralManager, CBPeripheral, BLE scanning/connecting, services, characteristics, background modes
core-motionCMMotionManager, CMPedometer, accelerometer, gyroscope, activity recognition, altitude
core-nfcNFCNDEFReaderSession, NFCTagReaderSession, NDEF reading/writing, background tag reading
dockkitDockAccessoryManager, camera subject tracking, motor control, framing
pencilkitPKCanvasView, PKDrawing, PKToolPicker, Apple Pencil drawing and annotation
realitykitRealityView, entities, anchors, ARKit world tracking, raycasting, scene understanding
sensorkitResearch-grade sensor data, ambient light, keyboard metrics, device usage (approved studies)

Platform Integration

SkillWhat it covers
appmigrationkitCross-platform data transfer, AppMigrationExtension export/import (iOS 26)
audioaccessorykitAudio accessory features, automatic switching, device placement (iOS 26.4)
browserenginekitAlternative browser engines (EU), process management, web content extensions
callkitCXProvider, CXCallController, PushKit VoIP registration, call directory extensions
cryptotokenkitTKTokenDriver, TKSmartCard, iOS 26 NFC smart cards, certificate-based auth
energykitElectricityGuidance, EnergyVenue, grid forecasts, load event submission, electricity insights
homekitHMHomeManager, accessories, rooms, actions, triggers, MatterSupport commissioning
permissionkitAskCenter, PermissionQuestion, child communication safety, CommunicationLimits
relevancekitWidget relevance signals, time/location-based relevance providers (watchOS 26)
shareplay-activitiesGroupActivity, GroupSession, GroupSessionMessenger, coordinated media playback

Gaming

SkillWhat it covers
gamekitGame Center, GKLocalPlayer, leaderboards, achievements, real-time and turn-based multiplayer
scenekitSCNView, SCNScene, 3D geometry, materials, lighting, physics, SceneView
spritekitSKScene, SKSpriteNode, SKAction, physics simulation, particle effects, SpriteView
tabletopkitMultiplayer spatial board games, pieces, cards, dice, Group Activities (visionOS)

Structure

Each skill follows the open Agent Skills standard:

skills/
  skill-name/
    SKILL.md              # Required — instructions and metadata
    references/           # Optional — detailed reference material
      some-topic.md

SKILL.md contains YAML frontmatter (name, description) and markdown instructions. The references/ folder holds longer examples, advanced patterns, and lookup tables that the main file points to.

This repository contains original instructional content and examples for Apple platform development. Where Apple frameworks, APIs, documentation, WWDC sessions, or trademarks are referenced, those materials remain the property of Apple Inc. The license for this repository applies to this project's original content only and does not claim ownership of or relicense Apple's documentation, trademarks, sample code, or other third-party materials.

Compatibility

These skills work with any agent that supports the Agent Skills standard, including:

Upgrading from v2.x

v3.0 is a major release. If you previously installed v2.x skills, note the following changes:

  • Skill count: 57 skills in v2.2.0, 76 skills in v3.0.0.

  • Skill renames: 12 existing skills renamed to use Apple Kit framework names. Old skill paths no longer resolve. Uninstall all skills and reinstall to upgrade.

    v2.x namev3.0 name
    live-activitiesactivitykit
    mapkit-locationmapkit
    photos-camera-mediaphotokit
    homekit-matterhomekit
    callkit-voipcallkit
    metrickit-diagnosticsmetrickit
    pencilkit-drawingpencilkit
    passkit-walletpasskit
    musickit-audiomusickit
    cloudkit-synccloudkit
    eventkit-calendareventkit
    realitykit-arrealitykit
  • 19 new Kit framework skills: avkit, gamekit, cryptokit, pdfkit, paperkit, spritekit, scenekit, financekit, accessorysetupkit, adattributionkit, carplay, appmigrationkit, browserenginekit, dockkit, sensorkit, tabletopkit, relevancekit, audioaccessorykit, cryptotokenkit.

  • New bundles: apple-kit-skills (all 39 Apple Kit framework skills) and ios-gaming-skills (GameKit, SpriteKit, SceneKit, TabletopKit).

  • PaperKit standalone: PaperKit content removed from pencilkit and is now its own paperkit skill.

  • Beta frameworks: permissionkit, energykit, paperkit, relevancekit, appmigrationkit, and audioaccessorykit require iOS/watchOS 26 beta and are subject to API changes before GM.

  • All skills remain self-contained: No skill references or depends on another.

To upgrade via the skills CLI:

npx skills add dpearson2699/swift-ios-skills

To upgrade Claude Code bundles, reinstall the bundles you use (old skill paths will no longer resolve).

Support

If these skills save you time or improve your workflow, you can support ongoing maintenance through GitHub Sponsors.

Support helps keep the collection current with new Apple releases, evolving framework APIs, updated examples, and compatibility work across Claude Code, Codex, Cursor, Copilot, and other agents.

Sponsors

Thanks to the following people for supporting this project:

Anthony Jr.

License

PolyForm Perimeter 1.0.0 -- see LICENSE

What this means in practice:

  • Using these skills to build your iOS app -- allowed
  • Using these skills inside a closed-source commercial workflow -- allowed
  • Forking the repo and contributing back -- allowed
  • Sharing the skills with a teammate -- allowed
  • Taking the skills, rebranding them as "Premium iOS Agent Skills," and selling them -- not allowed (that's a competing product)

This project is not affiliated with, endorsed by, or sponsored by Apple Inc.

商业与运营

中风险

  • 来源需自行核对维护者身份。
  • 未检测到明显脚本安装指令。
  • 可能需要外部 token、网络权限或第三方服务。
  • 未检测到高风险命令。
  • 扫描发现:1 条。

Codex — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/dpearson2699/swift-ios-skills.git
  3. 将 "skills/cloudkit" 文件夹复制到 Codex 的 skills 目录中。
  4. 重启 Codex 让新的 skill 生效。

Codex — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Codex 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Codex 让新的 skill 生效。

Claude Code — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/dpearson2699/swift-ios-skills.git
  3. 将 "skills/cloudkit" 文件夹复制到 Claude Code 的 skills 目录中。
  4. 重启 Claude Code 让新的 skill 生效。

Claude Code — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Claude Code 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Claude Code 让新的 skill 生效。

Cursor — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/dpearson2699/swift-ios-skills.git
  3. 将 "skills/cloudkit" 文件夹复制到 Cursor 的 skills 目录中。
  4. 重启 Cursor 让新的 skill 生效。

Cursor — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Cursor 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Cursor 让新的 skill 生效。

GitHub Copilot — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/dpearson2699/swift-ios-skills.git
  3. 将 "skills/cloudkit" 文件夹复制到 GitHub Copilot 的 skills 目录中。
  4. 重启 GitHub Copilot 让新的 skill 生效。

GitHub Copilot — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 GitHub Copilot 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 GitHub Copilot 让新的 skill 生效。

Windsurf — Git Clone 安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 克隆仓库:git clone https://github.com/dpearson2699/swift-ios-skills.git
  3. 将 "skills/cloudkit" 文件夹复制到 Windsurf 的 skills 目录中。
  4. 重启 Windsurf 让新的 skill 生效。

Windsurf — 手动复制安装

  1. 安装前请先查看来源仓库和风险报告。
  2. 从源仓库下载 SKILL.md 及相关文件。
  3. 在 Windsurf 的 skills 目录中创建新文件夹。
  4. 将所有 skill 文件复制到新文件夹中。
  5. 重启 Windsurf 让新的 skill 生效。
查看 SKILL.md 原文
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

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

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

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.

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

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

NSUbiquitousKeyValueStore

Simple key-value sync. Max 1024 keys, 1 MB total, 1 MB per value. Stores locally when iCloud is unavailable.

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

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.

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

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

发现问题?提交给管理员复核

评分:

评论 (0)

暂无评论,成为第一个评论者吧!