I'm using SwiftData with CloutKit with a very simple app. Data syncs between iOS, iPadOS, and visionOS, but not macOS. From what I can tell, macOS is never getting CK messages unless I'm running the app from Xcode.
I can listen for the CK messages and show a line in a debug overlay. This works perfectly when I run from Xcode. I can see the notifications and see updates in my app. However, if I just launch the app outside of Xcode I will never see any changes or notifications. It is as if the Mac app never even tries to contact CloudKit.
Schema has been deployed in the CloudKit console. The app is based on the multi-platform Xcode template. Again, only the macOS version has this issue. Is there some extra permission or setting I need to set up in order to use CloudKit on macOS?
@State private var publisher = NotificationCenter.default.publisher(for: NSPersistentCloudKitContainer.eventChangedNotification).receive(on: DispatchQueue.main)
.onReceive(publisher) { notification in
// Listen for changes in CK events
if let userInfo = notification.userInfo,
let event = userInfo[NSPersistentCloudKitContainer.eventNotificationUserInfoKey] as? NSPersistentCloudKitContainer.Event {
let message = "CloudKit Sync: \(event.type.rawValue) - \(event.succeeded ? "Success" : "Failed") - \(event.description)"
// Store for UI display
syncNotifications.append(message)
if syncNotifications.count > 10 {
syncNotifications.removeFirst()
}
}
}
.overlay(alignment: .topTrailing) {
if !syncNotifications.isEmpty {
VStack(alignment: .leading) {
ForEach(syncNotifications, id: \.self) { notification in
Text(notification)
.padding(8)
}
}
.frame(width: 800, height: 500)
.cornerRadius(8)
.background(Color.secondary.opacity(0.2))
.padding()
.transition(.move(edge: .top))
}
}
How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here
CloudKit
RSS for tagStore structured app and user data in iCloud containers that can be shared by all users of your app using CloudKit.
Posts under CloudKit tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I have developed an podcast app, where subscriped podcast & episodes synched with iCloud.
So its working fine with iOS & iPad with latest os version, but iCloud not synching in iPod with version 15.
Please help me to fix this.
Thanks
Devendra K.
For this code:
let status = try await container.accountStatus()
Seeing this error:
2025-05-08 15:32:00.945731-0500 localhost myAgent[2661]: (myDaemon.debug.dylib) [com.myDaemon.cli:networking] Error Domain=CKErrorDomain Code=6 "Error connecting to CloudKit daemon. This could happen for many reasons, for example a daemon exit, a device reboot, a race with the connection inactivity monitor, invalid entitlements, and more. Check the logs around this time to investigate the cause of this error." UserInfo={NSLocalizedDescription=Error connecting to CloudKit daemon. This could happen for many reasons, for example a daemon exit, a device reboot, a race with the connection inactivity monitor, invalid entitlements, and more. Check the logs around this time to investigate the cause of this error., CKRetryAfter=5, CKErrorDescription=Error connecting to CloudKit daemon. This could happen for many reasons, for example a daemon exit, a device reboot, a race with the connection inactivity monitor, invalid entitlements, and more. Check the logs around this time to investigate the cause of this error., NSUnderlyingError=0x600001bfc270 {Error Domain=NSCocoaErrorDomain Code=4099 UserInfo={NSDebugDescription=
I initially started the this process as System Daemon to see what would happen (which obviously does not have CloudKit features). Then moved it back to /Library/LaunchAgents/ and can't get rid of that error.
I see also following message from CloudKit daemon:
Ignoring failed attempt to get container proxy for <private>: Error Domain=NSCocoaErrorDomain Code=4099 UserInfo={NSDebugDescription=<private>}
Automatically retrying getting container proxy due to error for <private>: Error Domain=NSCocoaErrorDomain Code=4099 UserInfo={NSDebugDescription=<private>}
XPC connection interrupted for <private>
And this error for xpc service:
[0x130e074b0] failed to do a bootstrap look-up: xpc_error=[3: No such process]
If I start the same cli process directly from XCode, then it works just fine.
Does the CloudKit participant limit of 100 include the owner?
I have a CoreData model with two configuration - but several problems. Notably the viewContext only shows data from the .private configuration. Here is the setup:
The private configuration holds entities, for example, User and Course and the shared one holds entities, for example, Player and League. I setup the NSPersistentStoreDescriptions to use the same container but with a databaseScope of .private/.shared and with the configuration of "Private"/"Shared". loadPersistentStores() does not report an error.
If I try container.initializeCloudKitSchema() only the .private configuration produces CKRecord types. If I create a companion app using one configuration (w/ all entities) the schema initialization creates all CKRecord types AND I can populate some data in the .private and a created CKShare. I see that data in the CloudKit dashboard.
If I axe the companion app and run the real thing w/ two configurations, the viewContext only has the .private data. Why?
If when querying history I use NSPersistentHistoryTransaction.fetchRequest I get a nil return when using two configurations (but non-nil when using one).
Starting 20th March 2025, I see an increase in bandwidth and latency for one of my CloudKit projects.
I'm using NSPersistentCloudKitContainer to synchronise my data.
I haven't changed any CloudKit scheme during that time but shipped an update. Since then, I reverted some changes from that update, which could have led to changes in the sync behaviour.
Is anyone else seeing any issues?
I would love to file a DTS and use one of my credits for that, but unfortunately, I can't because I cannot reproduce it with a demo project because I cannot travel back in time and check if it also has an increase in metrics during that time.
Maybe an Apple engineer can green-light me filing a DTS request, please.
Hi all,
I am using SwiftData and cloudkit and I am having an extremely persistent bug.
I am building an education section on a app that's populated with lessons via a local JSON file. I don't need this lesson data to sync to cloudkit as the lessons are static, just need them imported into swiftdata so I've tried to use the modelcontainer like this:
static func createSharedModelContainer() -> ModelContainer {
// --- Define Model Groups ---
let localOnlyModels: [any PersistentModel.Type] = [
Lesson.self, MiniLesson.self,
Quiz.self, Question.self
]
let cloudKitSyncModels: [any PersistentModel.Type] = [
User.self, DailyTip.self, UserSubscription.self,
UserEducationProgress.self // User progress syncs
]
However, what happens is that I still get Lesson and MiniLesson record types on cloudkit and for some reason as well, whenever I update the data models or delete and reinstall the app on simulator, the lessons duplicate (what seems to happen is that a set of lessons comes from the JSON file as it should), and then 1-2 seconds later, an older set of lessons gets synced from cloudkit.
I can delete the old set of lessons if I just delete the lessons and mini lessons record types, but if I update the data model again, this error reccurrs.
Sorry, I don't know if I managed to explain this well but essentially I just want to stop the lessons and minilessons from being uploaded to cloudkit as I think this will fix the problem. Am I doing something wrong with the code?
I have transitioned to CKSyncEngine for syncing data to iCloud, and it is working quite well. I have a question regarding best practices for modifying and saving a CKRecord which already exists in the private or shared database.
In my current app, most CKRecords will never be modified after saving to the database, so I do not persist a received record locally after updating my local data model. In the rare event that the local data for that record is modified, I manually fetch the associated server record from the database, modify it, and then use CKSyncEngine to save the modified record.
As an alternative method, I can create a new CKRecord locally with the corresponding recordID and the modified data, and then use CKSyncEngine to attempt to save that record to the database. Doing so generates an error in the delegate method handleSentRecordZoneChanges, where I receive the local record I tried to save back inevent.failedRecordSaves with a .serverRecordChanged error, along with the corresponding server CKRecord. I can then update that server record with the local data and re-save using CKSyncEngine. I have not yet seen any issues when doing it this way.
The advantage of the latter method is that CKSyncEngine handles the entire database operation, eliminating the manual fetch step. My question is: is this an acceptable practice, or could this result in other unforeseen issues?
In core-data I have a contact and location entity. I have one-to-many relationship from contact to locations and one-to-one from location to contact. I create contact in a seperate view and save it. Later I create a location, fetch the created contact, and save it while specifying the relationship between location and contact contact and test if it actually did it and it works.
viewContext.perform {
do {
// Set relationship using the generated accessor method
currentContact.addToLocations(location)
try viewContext.save()
print("Saved successfully. Locations count:", currentContact.locations?.count ?? 0)
if let locs = currentContact.locations {
print("📍 Contact has \(locs.count) locations.")
for loc in locs {
print("➡️ Location: \(String(describing: (loc as AnyObject).locationName ?? "Unnamed"))")
}
}
} catch {
print("Failed to save location: \(error.localizedDescription)")
}
}
In my NSManagedObject class properties I have this : for Contact:
@NSManaged public var locations: NSSet?
for Location:
@NSManaged public var contact: Contact?
in my persistenceController I have:
for desc in [publicStore, privateStore] {
desc.setOption(true as NSNumber, forKey:
NSPersistentStoreRemoteChangeNotificationPostOptionKey)
desc.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
desc.setOption(true as NSNumber, forKey: NSMigratePersistentStoresAutomaticallyOption)
desc.setOption(true as NSNumber, forKey: NSInferMappingModelAutomaticallyOption)
desc.setOption(true as NSNumber, forKey: "CKSyncCoreDataDebug") // Optional: Debug sync
// Add these critical options for relationship sync
desc.setOption(true as NSNumber, forKey: "NSPersistentStoreCloudKitEnforceRecordExistsKey")
desc.setOption(true as NSNumber, forKey: "NSPersistentStoreCloudKitMaintainReferentialIntegrityKey")
// Add this specific option to force schema update
desc.setOption(true as NSNumber, forKey: "NSPersistentStoreRemoteStoreUseCloudKitSchemaKey")
}
When synchronization happens on CloudKit side, it creates CKRecords: CD_Contact and CD_Location. However for CD_Location it creates the relationship CD_contact as a string and references the CD_Contact. This I thought should have come as REFERENCE On the CD_Contact there is no CD_locations field at all. I do see the relationships being printed on coredata side but it does not come as REFERENCE on cloudkit. Spent over a day on this. Is this normal, what am I doing wrong here? Can someone advise?
I'm a first time developer for Swift, (getting on a bit!) but after programming in VB back in the late 90s I wanted to write an app for iPhone. I think I might have gone about it the wrong way, but I've got an app that works great on my iPhone or works great on my iPad. It saves the data persistently on device, but, no matter how much I try, what I read and even resorting to AI (ChatGPT & Gemini) I still can't get it to save the data on iCloud to synchronise between the two and work across the devices. I think it must be something pretty fundamental I'm doing (or more likely not doing) that is causing the issue.
I'm setting up my signing and capabilities as per the available instructions but I always get a fatal error. I think it might be something to do with making fields optional, but at this point I'm second guessing myself and feeling a complete failure. Any advice or pointers would be really gratefully appreciated. I like my app and would like eventually to get it on the App Store but at this point in time I feel it should be on the failed projects heap!
I've even tried a new Xcode project for iOS and asking it to use SwiftData and CloudKit - the default project should work - right? But it absolutely doesn't for me. Please send help!!
I have multiple app ids that are registered with Push Notification, however they do not hsow up in the Push Notification Console for testing.
This started on April 4.
System status says it's fixed, but I'm still having issues
I've noticed that SwiftData's @Relationship seems to potentially cause application crashes.
The crash error is shown in the image.
Since this crash appears to be random and I cannot reproduce it under specific circumstances, I can only temporarily highlight that this issue seems to exist.
@Model final class TrainInfo {
@Relationship(deleteRule: .cascade, inverse: \StopStation.trainInfo)
var stations: [StopStation]?
}
@Model final class StopStation {
@Relationship
var trainInfo: TrainInfo?
}
/// some View
var origin: StopStationDisplayable? {
if let train = train as? TrainInfo {
return train.stations?.first(where: { $0.isOrigin }) ?? train.stations?.first(where: { $0.isStarting })
}
return nil
}
// Some other function or property
func someFunction() {
if let origin, let destination {
// Function implementation
}
}
问题描述:
环境:
Xcode 版本: 16.3
*macOS 版本: 15.4
项目类型: SwiftUI App with SwiftData
问题摘要:
当在 Xcode 项目的 "Signing & Capabilities" 中为启用了 iCloud 能力的应用关联一个具体的 iCloud Container 时,即使代码中并未显式启用 CloudKit 同步(例如,未在 ModelConfiguration 中设置 cloudKitDatabase),SwiftData 的 ModelContainer 在应用启动初始化时也会立即失败并导致崩溃。如果仅启用 iCloud 能力但不选择任何 Container,应用可以正常启动。此问题在使用空的 Schema([]) 进行测试时依然稳定复现。
复现步骤 (使用最小复现项目 - MRE):
使用 Xcode 16.3 创建一个新的 SwiftUI App 项目 (例如,命名为 CloudKitCrashTest)。
在创建时不要勾选 "Host in CloudKit",或者,如果勾选了,先确保后续步骤覆盖相关设置。Storage 选择 None 或 SwiftData 均可复现。
修改 CloudKitCrashTestApp.swift 文件,添加 SwiftData 导入和基本的 ModelContainer 初始化逻辑。关键代码如下:
import SwiftUI
import SwiftData
@main
struct CloudKitCrashTestApp: App {
let sharedModelContainer: ModelContainer
init() {
// 使用空 Schema 进行诊断
let schema = Schema([])
// *不* 指定 cloudKitDatabase
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
sharedModelContainer = try ModelContainer(for: schema, configurations: [modelConfiguration])
print("ModelContainer created successfully.")
} catch {
// 在关联 Container 后,会在此处崩溃
fatalError("Could not create ModelContainer: \(error)")
}
}
var body: some Scene {
WindowGroup {
ContentView()
.modelContainer(sharedModelContainer)
}
}
}
// ... ContentView 定义 ...
进入项目的 Signing & Capabilities 标签页。
点击 + Capability 添加 iCloud。
在 iCloud 服务中,勾选 CloudKit。
此时,不要在 Containers 部分选择任何容器。
运行应用: 应用应该能够成功启动,并在控制台打印 "ModelContainer created successfully."。
停止应用。
回到 Signing & Capabilities -> iCloud -> Containers。
点击 + 添加一个新的自定义容器,或选择 Xcode 默认建议的容器。确保一个容器 ID 被明确选中。
再次运行应用: 应用现在会在启动时立即崩溃,fatalError 被触发。
预期结果:
即使在 Signing & Capabilities 中关联了 iCloud Container,应用也应该能够成功初始化 ModelContainer(尤其是当代码中未使用 cloudKitDatabase 或使用空 Schema 时),不应崩溃。
实际结果:
应用在 ModelContainer 初始化时崩溃,抛出 fatalError,错误信息为:
Could not create ModelContainer: SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer, _explanation: nil)
补充说明:
此问题在 iPhone 模拟器上稳定复现。
尝试清理构建文件夹 (Clean Build Folder)、删除派生数据 (Derived Data) 未能解决问题。
使用 Xcode 模板创建项目(勾选 "Host in CloudKit")并在之后手动取消选择 Container 可以运行,但一旦重新选择 Container 就会崩溃,现象一致。
这表明问题与 ModelContainer 初始化过程在检测到项目关联了具体 iCloud Container 标识符(可能涉及读取 .entitlements 文件或准备相关环境)时发生的内部错误有关,而不是由于实际的 CloudKit 同步代码或模型定义。
影响:
此 Bug 阻止了在当前的 Xcode 和 macOS 环境下开发和测试任何需要关联 iCloud Container 的 SwiftData 应用。
There's some logic in my app that first checks to see if a specific CloudKit record zone exists. If it doesn't, it creates the zone, and then my application continues on with its work.
The way I've implemented this right now is by catching the zoneNotFound error when I call CKDatabase#recordZone(for:) (docs) and creating the zone when that happens:
do {
try await db.recordZone(for: zoneID)
} catch let ckError as CKError
where [.zoneNotFound, .userDeletedZone].contains(ckError.code)
{
// createZone is a helper function
try await createZone(zoneID: zoneID, context: context)
}
This works great, but every time I do this, an error is logged in CloudKit Console, which creates a lot of noise and makes it harder to see real errors.
Is there a way to do this without explicitly triggering a CloudKit error?
I just found CKDatabase#recordZones(for:) (docs), which seems like it returns an empty array instead of throwing an error if the zone doesn't exist.
Will calling that and looking for a non-empty array work just as well, but without logging lots of errors in the console?
My newly released App Snapshot-Chess-Move, #1592848671, is not creating a public database of chess moves as I expect. What steps do I need to do inorder for my App to be using a public database. It appears as if each of my iOS devices, iPhone, iPad and Mac mini each have a private database of chess moves. When I change my data on the iPad, I expect the new data to appear (with slight delays) on the Mac.. I do not know what to do next. Please help me. This was working in Development mode but not in Production when I submitted my App for release.
UPDATE:
The cloud data is copied locally to a @Quary variable and updated by using .insert, .delete and .save commands. So, I deleted and re-downloaded my apps on each device, iPad, iPhone, and Mac and obtained the same cloud data. So how do users get the most recent copy of the cloud. Do they need to delete their App and start over? Is there a .update command that can do this updating for me? Also, I pushed the App out of the background and restarted the App to obtain the updated cloud data.
So i created an App and for some time it was working fine. The app has features to show pdf to users without logging in. I needed to upload all data to cloudkit on public database.
I was not having knowledge that there are 2 mode being a noob in coding so after i saved all records in development mode in cloudkit when i published my app, i was not able to see them (Reason because live mode works in Production mode).
So i need help now to transfer data from development mode to production mode or any app or code that can help me upload all data in production mode.
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
CloudKit
CloudKit Dashboard
CloudKit Console
I'm trying to set up server-to-server authentication with CloudKit Web Services, but keep getting AUTHENTICATION_FAILED errors. I've tried multiple environment settings and debugging approaches without success.
What I've Tried
I created a Swift script to test the connection. Here's the key part that handles the authentication:
// Get current ISO 8601 date
let iso8601Formatter = ISO8601DateFormatter()
iso8601Formatter.formatOptions = [.withInternetDateTime]
let dateString = iso8601Formatter.string(from: Date())
// Create SHA-256 hash of request body
let bodyHash = SHA256.hash(data: bodyData).compactMap { String(format: "%02x", $0) }.joined()
// Get path from URL
let path = request.url?.path ?? "/"
// String to sign
let method = request.httpMethod ?? "POST"
let stringToSign = "\(method):\(path):\(dateString):\(bodyHash)"
// Sign the string with EC private key
let signature = try createSignature(stringToSign: stringToSign)
// Add headers
request.setValue(dateString, forHTTPHeaderField: "X-Apple-CloudKit-Request-ISO8601Date")
request.setValue(KEY_ID, forHTTPHeaderField: "X-Apple-CloudKit-Request-KeyID")
request.setValue(signature, forHTTPHeaderField: "X-Apple-CloudKit-Request-SignatureV1")
}
I've made a request to this endpoint:
What's Happening
I get a 401 status with this response:
"uuid" : "173179e2-c5a5-4393-ab4f-3cec194edd1c",
"serverErrorCode" : "AUTHENTICATION_FAILED",
"reason" : "Authentication failed"
}
What I've Verified
The key validates correctly and generates signatures
The date/time is synchronized with the server
The key ID matches what's in CloudKit Dashboard
I've tried all three environments: development, Development (capital D), and production
The container ID is formatted correctly
Debug Information
My debugging reveals:
The EC key is properly formatted (SEC1 format)
Signature generation works
No time synchronization issues between client and server
All environment tests return the same 401 error
Questions
Has anyone encountered similar issues with CloudKit server-to-server authentication?
Are there specific container permissions needed for server-to-server keys?
Could there be an issue with how the private key is formatted or processed?
Are there any known issues with the CloudKit Web Services API that might cause this?
Any help would be greatly appreciated!
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
CloudKit
Cloud and Local Storage
CloudKit JS
Hi Developer Community,
I'm experiencing a critical issue with CloudKit schema deployment that's blocking my app release. I've been trying to resolve this for several days and would appreciate any assistance from the community or Apple engineers.
Issue Description
I'm unable to deploy my CloudKit schema from development to production environment. When attempting to deploy through the CloudKit Dashboard, I either get an "Internal Error" message or the deployment button is disabled.
Environment Details
App: Reef Trak (Reef aquarium tracking app)
CloudKit Container: ************
Development Environment: Schema fully defined and working correctly
Production Environment: No schema deployed (confirmed in dashboard)
What I've Tried
Using the "Deploy Schema to Production" button in CloudKit Dashboard (results in "Internal Error")
Exporting schema from development and importing to production (fails)
Using CloudKit CLI tools with API token (results in "invalid-scope" errors)
Waiting 24-48 hours between attempts in case of propagation delays
Current Status
App works perfectly in development environment (when run from Xcode)
In TestFlight/sideloaded builds (production environment), the app attempts to fetch records but fails with "Did not find record type: Tank" errors
Log snippet showing the issue:
[2025-03-21] [CloudKit] Schema creation failed: Error saving record <CKRecordID: 0x******; recordName=SchemaSetup_Tank_-**---****, zoneID=_defaultZone:defaultOwner> to server: Cannot create new type Tank in production schema [2025-03-21] [CloudKit] Failed to create schema for Tank after 3 attempts [2025-03-21] [CloudKit] Error creating schema for Tank: Error saving record <CKRecordID: 0x****; recordName=SchemaSetup_Tank_---**-**********, zoneID=_defaultZone:defaultOwner> to server: Cannot create new type Tank in production schema
App Architecture & Critical Impact
My app "Reef Trak" is built around a core data model where the "Tank" entity serves as the foundational element of the entire application architecture. The Tank entity is not just another data type - it's the primary container that establishes the hierarchical relationship for all other entities:
All parameter measurements (pH, temperature, salinity, etc.) are associated with specific tanks
All maintenance tasks and schedules are tank-specific
All livestock (fish, corals, invertebrates) exist within the context of a tank
All user achievements and progress tracking depend on tank-related activities
Without the Tank schema being properly deployed to production, users experience what appears to be a completely empty application, despite successful authentication and CloudKit connection. The app shows "Successfully retrieved iCloud data" but displays no content because:
The Tank record type doesn't exist in production
Without Tanks, all child entities (even if their schemas existed) have no parent to associate with
This creates a cascading failure where no data can be displayed or saved
This issue effectively renders the entire application non-functional in production, despite working flawlessly in development. Users are left with an empty shell of an app that cannot fulfill its core purpose of reef tank management and monitoring.
The inability to deploy the Tank schema to production is therefore not just a minor inconvenience but a complete blocker for the app's release and functionality.
Questions
Is there an alternative method to deploy schema to production that I'm missing?
Could there be an issue with my account permissions or container configuration?
Are there known issues with the CloudKit Dashboard deployment functionality?
What's the recommended approach when the dashboard deployment fails?
I've also submitted a Technical Support Incident, but I'm hoping to get this resolved quickly as it's blocking my App Store release.
Thank you for any assistance!
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
CloudKit
CloudKit Dashboard
CloudKit Console
cktool
I've recently added iCloud backup on my chat app. Conversations are backing up fine but some users are losing their chats and when I see the telemetry it show "BAD_REQUEST" error. I couldn't find any details or solution for it.
Does anyone has any idea what it could be? My development scheme is already fully deployed to production.
Topic:
Developer Tools & Services
SubTopic:
Xcode Cloud
Tags:
CloudKit
iCloud Drive
CloudKit Console