CloudKit

RSS for tag

Store 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

Post

Replies

Boosts

Views

Activity

CloudKit Sync with TestFlight
I'm working on a new app with SwiftData and now adding CloudKit Sync. Everything is working fine in the simulator against the development CloudKit Schema. I successfully deployed the schema to production. However, the TestFlight builds fail against production. This is what I see in the logs, but I haven't been able to find info on how to fix it. Help appreciated. CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2205): <private> - Never successfully initialized and cannot execute request '<private>' due to error: Error Domain=CKErrorDomain Code=2 "CKInternalErrorDomain: 1011" UserInfo={ContainerID=<private>, NSDebugDescription=CKInternalErrorDomain: 1011, CKPartialErrors=<private>, RequestUUID=<private>, NSLocalizedDescription=<private>, CKErrorDescription=<private>, NSUnderlyingError=0x1078e9fe0 {Error Domain=CKInternalErrorDomain Code=1011 UserInfo={CKErrorDescription=<private>, NSLocalizedDescription=<private>, CKPartialErrors=<private>}}} CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1153): <private>: Successfully set up CloudKit integration for store (<private>): <private> CoreData+CloudKit: -[NSCloudKitMirroringDelegate _enqueueRequest:]_block_invoke(1035): Failed to enqueue request: <private> Error Domain=NSCocoaErrorDomain Code=134417 UserInfo={NSLocalizedFailureReason=<private>}
0
0
27
1d
SwiftData & CloudKit: Arrays of Codable Structs Causing NSKeyedUnarchiveFromData Error
I have SwiftData models containing arrays of Codable structs that worked fine before adding CloudKit capability. I believe they are the reason I started seeing errors after enabling CloudKit. Example model: @Model final class ProtocolMedication { var times: [SchedulingTime] = [] // SchedulingTime is Codable // other properties... } After enabling CloudKit, I get this error logged to the console: 'NSKeyedUnarchiveFromData' should not be used to for un-archiving and will be removed in a future release CloudKit Console shows this times data as "plain text" instead of "bplist" format. Other struct/enum properties display correctly (I think) as "bplist" in CloudKit Console. The local SwiftData storage handled these arrays fine - this issue only appeared with CloudKit integration. What's the recommended approach for storing arrays of Codable structs in SwiftData models that sync with CloudKit?
5
1
182
4d
SwiftData with CloudKit in Widgets
Good morning everyone! Today I have a question about using SwiftData with CloudKit and Widgets. I recently set up my project for SwiftData and CloudKit synchronization, but for some reason, I’m not able to give my Widget access to this data. CloudKit works perfectly fine for my main app, but the Widget only shows placeholder data(the placeholder data which were defined in the get functions as catch, this is sure). I have set the CloudKit capability for my Widget extension and tried fetching data with the get-functions in the code below. I also ensured that the data model files are members of the Widget extension target and that the Widget extension uses the same CloudKit container as the main app. I wondered if it is possible and reasonable to save a copy of my CloudKit data in an App Group container, but in that case, the information shown in the Widget are not always up-to-date, so a solution that fetches data directly from CloudKit would be better. Has anyone had experience with this case? I couldn’t find much information about this problem online. In the code below, many parts have been deleted or altered because they are not relevant to the problem, as they don’t fetch data. The variables, functions, and data models in the code may sometimes have German names, but I hope you can still understand it. Thanks for your help! struct Provider: AppIntentTimelineProvider { //[Placeholder and snapshot] func timeline(for configuration: ConfigurationAppIntent, in context: Context) async -> Timeline<CleverEntry> { let entry = await loadAllVariables() return Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(60 * 5))) } @MainActor private func getExam() -> [PruefungM] { //Old, local version /* guard let modelContainer = try? ModelContainer(for: PruefungM.self) else { return [] } let descriptor = FetchDescriptor<PruefungM>() let PRF = try? modelContainer.mainContext.fetch(descriptor) return PRF ?? [] */ do { let configuration = ModelConfiguration(cloudKitDatabase: .private("iCloud.my_bundle_id")) let container = try ModelContainer( for: PruefungM.self, configurations: configuration ) let descriptor = FetchDescriptor<PruefungM>() return try container.mainContext.fetch(descriptor) } catch { print("❌ Error(CloudKit): \(error)") return [] } } @MainActor private func getHAF() -> [HausaufgabeM] { do { let configuration = ModelConfiguration(cloudKitDatabase: .private("iCloud.my_bundle_id")) let container = try ModelContainer( for: HausaufgabeM.self, configurations: configuration ) let descriptor = FetchDescriptor<HausaufgabeM>() return try container.mainContext.fetch(descriptor) } catch { print("❌ Error (CloudKit): \(error)") return [] } } @MainActor private func loadAllVariables() -> CleverEntry { print("Function started") let HAF = getHAF() let PRF = getExam() //handling and returning the data } }
1
0
122
1w
Interactive Widget with SwiftData Not Triggering iCloud Sync
Hello everyone, I'm developing an app for iOS 18 using SwiftData, with iCloud synchronization enabled. My app also includes an interactive widget that allows users to mark tasks as complete, similar to Apple's Reminders widget. I'm facing a specific issue with how iCloud sync is triggered when changes are made from the widget. My Setup: Xcode 16 Swift 6 / iOS 18 SwiftData with iCloud Sync enabled. An interactive widget using App Intents to modify the SwiftData model. What's working correctly: App to Widget (Same Device): If I mark a task as complete in the main app, the widget on the same device updates instantly. Widget to App (Same Device): If I mark a task as complete using the interactive widget, the main app on the same device reflects this change immediately. App to App (Across Devices): If I make a change in the app on my iPhone, it syncs correctly via iCloud and appears in the app on my iPad. The Problem: The synchronization issue occurs specifically when an action is initiated from the widget and needs to be reflected on other devices, or when a change from another device needs to be reflected in the widget. Widget Change Not Syncing to Other Devices: If I mark a task as complete in the widget on my iPhone, the change does not sync to my iPad. The task on the iPad only updates after I manually open the main app on the iPhone. Remote Change Not Syncing to Widget: Similarly, if I mark a task as complete in the app on my iPad, the widget on my iPhone does not update to show this change. The widget only refreshes with the correct state after I open the main app on the iPhone. It seems that the widget's AppIntent correctly modifies the local SwiftData store, but this action isn't triggering the necessary background process to push the changes to iCloud. The sync only seems to happen when the main app, with its active ModelContainer, is brought to the foreground. My goal is for any change made in the widget to be reflected across all of the user's devices in near real-time, without requiring them to launch the main app to initiate the sync. Is there a specific API I need to call from my AppIntent to force a SwiftData sync, or a project capability I might be missing to allow the widget extension to trigger iCloud pushes? Any help or guidance would be greatly appreciated. Thank you!
1
0
76
1w
SwiftData and CloudKit: NSKeyedUnarchiveFromData Error
I just made a small test app that uses SwiftData with CloudKit capability. I created a simple Book model as seen below. It looks like enums and structs when used with CloudKit capability all trigger this error: 'NSKeyedUnarchiveFromData' should not be used to for un-archiving and will be removed in a future release I fixed the error by using genreRaw String and using a computed property to use it in the app, but it popped back up after adding the ReadingProgress struct Should I ignore the error and assume Apple still supports enums and codable structs when using SwiftData with CloudKit? import SwiftData @Model class Book { var title: String = "" var author: String = "" var genreRaw: String = Genre.fantasy.rawValue var review: String = "" var rating: Int = 3 var progress: ReadingProgress? var genre: Genre { get { Genre(rawValue: genreRaw) ?? Genre.fantasy } set { genreRaw = newValue.rawValue } } init(title: String, author: String, genre: Genre, review: String, rating: Int, progress: ReadingProgress? = nil) { self.title = title self.author = author self.genre = genre self.review = review self.rating = rating self.progress = progress } } struct ReadingProgress: Codable { var currentPage: Int var totalPages: Int var isFinished: Bool var percentComplete: Double { guard totalPages > 0 else { return 0 } return Double(currentPage) / Double(totalPages) * 100 } } enum Genre: String, Codable, CaseIterable { case fantasy case scienceFiction case mystery case romance var displayName: String { switch self { case .fantasy: return "Fantasy" case .scienceFiction: return "Science Fiction" case .mystery: return "Mystery" case .romance: return "Romance" } } }
1
1
260
1w
CloudKit with Unreal Engine
Hi everyone, Im trying to set up CloudKit for my Unreal Engine 5.4 project but seem to be hitting some roadblocks on how to set up the Record Types. From my understanding I need to set up a "file" record type with a "contents" asset field - but even with this it doesn't seem to work :( Any unreal engine devs with some experience on this who could help me out? Thanks!
0
0
54
1w
CloudKit Query on Custom Indexed Field fails with misleading "createdBy is not queryable" error
Hello everyone, I am experiencing a persistent authentication error when querying a custom user profile record, and the error message seems to be a red herring. My Setup: I have a custom CKRecord type called ColaboradorProfile. When a new user signs up, I create this record and store their hashed password, salt, nickname, and a custom field called loginIdentifier (which is just their lowercase username). In the CloudKit Dashboard, I have manually added an index for loginIdentifier and set it to Queryable and Searchable. I have deployed this schema to Production. The Problem: During login, I run an async function to find the user's profile using this indexed loginIdentifier. Here is the relevant authentication code: func autenticar() async { // ... setup code (isLoading, etc.) let lowercasedUsername = username.lowercased() // My predicate ONLY filters on 'loginIdentifier' let predicate = NSPredicate(format: "loginIdentifier == %@", lowercasedUsername) let query = CKQuery(recordType: "ColaboradorProfile", predicate: predicate) // I only need these specific keys let desiredKeys = ["password", "passwordSalt", "nickname", "isAdmin", "isSubAdmin", "username"] let database = CKContainer.default().publicCloudDatabase do { // This is the line that throws the error let result = try await database.records(matching: query, desiredKeys: desiredKeys, resultsLimit: 1) // ... (rest of the password verification logic) } catch { // The error always lands here logDebug("Error authenticating with CloudKit: \(error.localizedDescription)") await MainActor.run { self.errorMessage = "Connection Error: \(error.localizedDescription)" self.isLoading = false self.showAlert = true } } } The Error: Even though my query predicate only references loginIdentifier, the catch block consistently reports this error: Error authenticating with CloudKit: Field 'createdBy' is not marked queryable. I know createdBy (the system creatorUserRecordID) is not queryable by default, but my query isn't touching that field. I already tried indexing createdBy just in case, but the error persists. It seems CloudKit cannot find or use my index for loginIdentifier and is incorrectly reporting a fallback error related to a system field. Has anyone seen this behavior? Why would CloudKit report an error about createdBy when the query is explicitly on an indexed, custom field? I'm new to Swift and I'm struggling quite a bit. Thank you,
0
0
121
1w
Using SwiftData with a local and CloudKit backed configuration at the same time
I'm trying to set up an application using SwiftData to have a number of models backed by a local datastore that's not synced to CloudKit, and another set of models that is. I was able to achieve this previously with Core Data using multiple NSPersistentStoreDescription instances. The set up code looks something like: do { let fullSchema = Schema([ UnsyncedModel.self, SyncedModel.self, ]) let localSchema = Schema([UnsyncedModel.self]) let localConfig = ModelConfiguration(schema: localSchema, cloudKitDatabase: .none) let remoteSchema = Schema([SyncedModel.self]) let remoteConfig = ModelConfiguration(schema: remoteSchema, cloudKitDatabase: .automatic) container = try ModelContainer(for: fullSchema, configurations: localConfig, remoteConfig) } catch { fatalError("Failed to configure SwiftData container.") } However, it doesn't seem to work as expected. If I remove the synced/remote schema and configuration then everything works fine, but the moment I add in the remote schema and configuration I get various different application crashes. Some examples below: A Core Data error occurred." UserInfo={Reason=Entity named:... not found for relationship named:..., Fatal error: Failed to identify a store that can hold instances of SwiftData._KKMDBackingData<...> Has anyone ever been able to get a similar setup to work using SwiftData?
0
0
194
1w
CloudKit shares and iOS26 public beta (23A5336a)
I am developing an app that uses CloudKit sharing. I recently upgraded my iPad to use 23A5336a. After that upgrade, I can no longer accept a share that is sent to me. I have rebooted the iPad and logged out of the iCloud account and logged back in. Every time I get a share link and tap it, it says: " The owner stopped sharing or your account (***) doesn't have permission to open it" This same code, running on the iOS26 device can share with device running iOS18. Is this a known defect? Anything I can do to help resolve this issue?
1
0
159
1w
SwiftData - Cloudkit stopped syncing
I have an app that from day 1 has used Swiftdata and successfully sync'd across devices with Cloudkit. I have added models to the data in the past and deployed the schema and it continued to sync across devices. Sometime I think in June.2025 I added a new model and built out the UI to display and manage it. I pushed a version to Test Flight (twice over a matter of 2 versions and a couple of weeks) and created objects in the new model in Test Flight versions of the app which should push the info to Cloudkit to update the schema. When I go to deploy the schema though there are no changes. I confirmed in the app that Cloudkit is selected and it's point to the correct container. And when I look in Cloudkit the new model isn't listed as an indes. I've pushed deploy schema changes anyway (more than once) and now the app isn't sync-ing across devices at all (even the pre-existing models aren't sync-ing across devices). I even submitted the first updated version to the app store and it was approved and released. I created objects in the new model in production which I know doesn't create the indexes in the development environment. But this new model functions literally everywhere except Cloudkit and I don't know what else to do to trigger an update.
3
1
149
2w
Core Data + CKSyncEngine with Swift 6 — concurrency, Sendable, and best practices validation
Hi everyone, I’ve been working on migrating my app (SwimTimes, which helps swimmers track their times) to use Core Data + CKSyncEngine with Swift 6. After many iterations, forum searches, and experimentation, I’ve created a focused sample project that demonstrates the architecture I’m using. The good news: 👉 I believe the crashes I was experiencing are now solved, and the sync behavior is working correctly. 👉 The demo project compiles and runs cleanly with Swift 6. However, before adopting this as the final architecture, I’d like to ask the community (and hopefully Apple engineers) to validate a few critical points, especially regarding Swift 6 concurrency and Core Data contexts. Architecture Overview Persistence layer: Persistence.swift sets up the Core Data stack with a main viewContext and a background context for CKSyncEngine. Repositories: All Core Data access is abstracted into repository classes (UsersRepository, SwimTimesRepository), with async/await methods. SyncEngine: Wraps CKSyncEngine, handles system fields, sync tokens, and bridging between Core Data entities and CloudKit records. ViewModels: Marked @MainActor, exposing @Published arrays for SwiftUI. They never touch Core Data directly, only via repositories. UI: Simple SwiftUI views bound to the ViewModels. Entities: UserEntity → represents swimmers. SwimTimeEntity → times linked to a user (1-to-many). Current Status The project works and syncs across devices. But there are two open concerns I’d like validated: Concurrency & Memory Safety Am I correctly separating viewContext (main/UI) vs. background context (used by CKSyncEngine)? Could there still be hidden risks of race conditions or memory crashes that I’m not catching? Swift 6 Sendable Compliance Currently, I still need @unchecked Sendable in the SyncEngine and repository layers. What is the recommended way to fully remove these workarounds and make the code safe under Swift 6’s stricter concurrency rules? Request Please review this sample project and confirm whether the concurrency model is correct. Suggest how I can remove the @unchecked Sendable annotations safely. Any additional code improvements or best practices would also be very welcome — the intention is to share this as a community resource. I believe once finalized, this could serve as a good reference demo for Core Data + CKSyncEngine + Swift 6, helping others migrate safely. Environment iOS 18.5 Xcode 16.4 macOS 15.6 Swift 6 Sample Project Here is the full sample project on GitHub: 👉 [https://github.com/jarnaez728/coredata-cksyncengine-swift6] Thanks a lot for your time and for any insights! Best regards, Javier Arnáez de Pedro
1
0
339
2w
Core Data initialization causes app to deadlock on startup
Users have been reporting that the TestFlight version of my app (compiled with Xcode 26 Beta 6 17A5305f) is sometimes crashing on startup. Upon investigating their ips files, it looks like Core Data is locking up internally during its initialization, resulting in iOS killing my app. I have not recently changed my Core Data initialization logic, and it's unclear how I should proceed. Is this a known issue? Any recommended workaround? I have attached the crash stack below. Thanks! crash_log.txt
2
0
127
2w
SwiftData and CloudKit
Recently I've been working on a demo project called iLibrary. The main goal was to learn more about CloudKit and SwiftData. After a while I noticed that there were some hangs/freezes when running the app in debug mode. I first tried this with Xcode 15.4 and iOS 17.5. Here the hang only appears at the beginning, but only for a few seconds. But when I exit debug mode, there are no more hangs. With Xcode 16 beta 4 and iOS 18 it looks completely different. In this case, the hangs and freezes are always present, whether in debug mode or not. And it's not just at the beginning, it's throughout the app. I'm aware that this is still a beta, but I still find this weird. And when I profile this I see that the main thread gets quite overloaded. Interestingly, my app doesn't have that many operations going on. So I guess something with the sync of SwiftData or my CloudKitManger where I fetch some records from the public database is not running fine. Lastly, I wanted to delete the iCloud app data. So I went to Settings and tried to delete it, but it didn't work. Is this normal? Does anyone have any idea what this could be? Or has anyone encountered this problem as well? I'd appreciate any support. My project: https://github.com/romanindermuehle/iLibrary
9
5
1.5k
2w
Automatic Code Signing Error
I am trying to update an old UIKit/CoreData app and am (among other changes) adding CloudKit synchronization support. I enabled CloudKit (ie, set up a new CloudKit domain, enabled CloudKit, Background Mode Remote Notifications, and Push Notifications. When I did this, automatic code signing failed. (see attached for the messages). I tried creating and downloading a new provisioning profile, but that did not help. FB19742743 Can someone help me? I have absolutely no idea of what to do next to get this app signed (and hopefully back into the AppStore soon).
2
0
167
3w
ZoneSharing CloudKit UI
I am trying to use Zone Sharing in my SwiftUI app. I have been attempting to get the UICloudSharingController to show an initial share screen to pick users and the mechanism to send the invitation. From the documentation, it appears that the UICloudSharingController .init(preparationHandler:) API is deprecated so I am not using that approach. Following the Apple documentation, I am creating a Zone Share and NOT saving it and presenting using the UICloudSharingController(share:container:) API. However, this presents a UI that is the 'mgmt' API for a Share. I can get to the UI I was expecting by tapping on the 'Share with More People' option, but I want to start on that screen for the user when they have not shared this before. So, I found an example app from Apple at: https://github.com/apple/sample-cloudkit-zonesharing. It has the same behavior. So we can simply discuss this problem based on that example code. How do I get the next View presented when tapping 'Share Group' to be the invitation for new users screen? Here is the UI it presents initially: And here is the UI (on the bottom half of the screen) I am trying to start the share process with: Thanks, Charlie
3
0
85
3w
Why is CKModifyRecordsOperation to batch delete records in CloudKit not deleting records?
My Code: let op = CKModifyRecordsOperation(recordIDsToDelete:recordIDsToDelete) op.modifyRecordsCompletionBlock = { _, deleteRecordIDs, error in if error == nil { print("successful delete deleteRecordIDS = \(deleteRecordIDs)") } else { print("delete error = \(error?.localizedDescription)") } } op.database = CKContainer.default().privateCloudDatabase op.qualityOfService = .userInitiated CKContainer.default().privateCloudDatabase.add(op) My problem is that CKRecord are not deleted once I reinstall the app: when I reinstall the app and try to delete a CloudKit record, the method is executed successfully (error is nil) but the records are still in CloudKit Dashboards.
2
0
186
3w
CloudKit console fails to query indexed records in Production
"No records found" If I create a new record on the console, I can copy the record name. I can then query for recordName and get that individual record back. BUT no other queries work. I cannot query all records. I cannot query by individual property. Just returns "no records found" Seems like my indexes got messed up. Is there a way to reset indexes on prod? This is on a coredata.cloudkit managed zone.
1
0
72
3w
CloudKit: Records not indexing
Since publishing new record types to my CloudKit schema in production, a previously unchanged record type has stopped indexing new records. While records of this type are successfully saved without errors, they are not returned in query results—they can only be accessed directly via their recordName. This issue occurs exclusively in the Production environment, both in the CloudKit Console and our iOS app. The problem began on July 21, 2025, and continues to persist. The issue affects only new records of this specific record type; all other types are indexing and querying as expected. The affected record's fields are properly configured with the appropriate index types (e.g., QUERYABLE) and have been not been modified prior to publishing the schema. With this, are there any steps I should take to restore indexing functionality for this record type in Production? There have been new records inserted, and I would prefer to not have to reset the production database, if possible.
4
1
180
3w
SwiftData migration error: NSCloudKitMirroringDelegate are not reusable
Hello everyone, I used SwiftData for v1 of an app and am now trying to make changes to the schema for v2. I created the v2 schema that adds a property to one of the models. I need to populate the new property so I made a custom migration using didMigrate. However that doesn't seem to matter what I do in the migration because creating the ModelContainer throws an error before didMigrate ever gets called. The error is: Unresolved error loading container Error Domain=NSCocoaErrorDomain Code=134060 "A Core Data error occurred." UserInfo={NSLocalizedFailureReason=Instances of NSCloudKitMirroringDelegate are not reusable and should have a lifecycle tied to a given instance of NSPersistentStore.} Higher up in the Xcode output I see things like this (in order): Request 'D25A8CB8-7341-4FA8-B2F8-3DE2D35B5273' was cancelled because the store was removed from the coordinator. BUG IN CLIENT OF CLOUDKIT: Registering a handler for a CKScheduler activity identifier that has already been registered CloudKit setup failed because it couldn't register a handler for the export activity. There is another instance of this persistent store actively syncing with CloudKit in this process. How can I know from this output what I am doing incorrectly? Any idea what I should take a look at or try to do differently? This is a simple app with three models and nothing fancy. The only change in the schema is to add a property. The new property is declared as optional and has an inverse that is also declared as optional. Thanks for any insight!
16
7
1.2k
Aug ’25