iCloud & Data

RSS for tag

Learn how to integrate your app with iCloud and data frameworks for effective data storage

CloudKit Documentation

Posts under iCloud & Data subtopic

Post

Replies

Boosts

Views

Activity

Mac Assigning NSManagedObject to NSPersistentStore
Hello, I have a iOS app I was looking at porting to Mac. I'm having an issue with both the Mac (Designed for iPad) and Mac Catalyst Destinations. I can't test Mac due to too many build issues. I'm trying to assign a new NSManagedObject into a NSPersistentStore. let object = MyObject(context: context) context.assign(object, to: nsPersistentStore) This works fine for iOS/iOS Simulator/iPhone/iPad. But on the Mac it's crashing with FAULT: NSInvalidArgumentException: Can't assign an object to a store that does not contain the object's entity.; { Thread 1: "Can't assign an object to a store that does not contain the object's entity."
0
0
10
9h
CloudKit, CoreData and Swift 6 for sharing between users
I have started from here: Apple's guide on the sharing core data objects between iCloud users and I have created a sample project that has Collections and Items. Everything works great while I stay on Swift 5, like with the initial project. I would like to migrate to Swift 6 (Default Actor Isolaton @MainActor, Approachable Concurrency: Yes) on the project and I am stuck at extension CDCollection: Transferable { ... }. When compiling with Swift 5, there is a warning: Conformance of 'NSManagedObject' to 'Sendable' is unavailable in iOS; this is an error in the Swift 6 language mode. After resolving almost all compile-time warnings I'm left with: Conformance of 'CDCollection' to protocol 'Transferable' crosses into main actor-isolated code and can cause data races. Which I don't think will work, because of the warning shown above. It can be worked around like: nonisolated extension CDCollection: Transferable, @unchecked Sendable Then there are errors: let persistentContainer = PersistenceController.shared.persistentContainer Main actor-isolated static property 'shared' can not be referenced from a nonisolated context. I've created the following class to have a Sendable object: struct CDCollectionTransferable: Transferable { var objectID: NSManagedObjectID var persistentContainer: NSPersistentCloudKitContainer public static var transferRepresentation: some TransferRepresentation { CKShareTransferRepresentation { collectionToExport in let persistentContainer = collectionToExport.persistentContainer let ckContainer = CloudKitProvider.container var collectionShare: CKShare? if let shareSet = try? persistentContainer.fetchShares( matching: [collectionToExport.objectID]), let (_, share) = shareSet.first { collectionShare = share } /** Return the existing share if the collection already has a share. */ if let share = collectionShare { return .existing(share, container: ckContainer) } /** Otherwise, create a new share for the collection and return it. Use uriRepresentation of the object in the Sendable closure. */ let collectionURI = collectionToExport.objectID .uriRepresentation() return .prepareShare(container: ckContainer) { let collection = await persistentContainer.viewContext .perform { let coordinator = persistentContainer.viewContext .persistentStoreCoordinator guard let objectID = coordinator?.managedObjectID( forURIRepresentation: collectionURI ) else { fatalError( "Failed to return the managed objectID for: \(collectionURI)." ) } return persistentContainer.viewContext.object( with: objectID ) } let (_, share, _) = try await persistentContainer.share( [collection], to: nil ) return share } } } } And I'm able to compile and run the app with this change: let transferable = CDCollectionTransferable( objectID: collection.objectID, persistentContainer: PersistenceController.shared .persistentContainer ) ToolbarItem { ShareLink( item: transferable, preview: SharePreview("Share \(collection.name)!") ) { MenuButtonLabel( title: "New Share", systemImage: "square.and.arrow.up" ) } } The app crashes when launched with libdispatch.dylib`_dispatch_assert_queue_fail: 0x1052c6ea4 <+0>: sub sp, sp, #0x50 0x1052c6ea8 <+4>: stp x20, x19, [sp, #0x30] 0x1052c6eac <+8>: stp x29, x30, [sp, #0x40] 0x1052c6eb0 <+12>: add x29, sp, #0x40 0x1052c6eb4 <+16>: adrp x8, 63 0x1052c6eb8 <+20>: add x8, x8, #0xa0c ; "not " 0x1052c6ebc <+24>: adrp x9, 62 0x1052c6ec0 <+28>: add x9, x9, #0x1e5 ; "" 0x1052c6ec4 <+32>: stur xzr, [x29, #-0x18] 0x1052c6ec8 <+36>: cmp w1, #0x0 0x1052c6ecc <+40>: csel x8, x9, x8, ne 0x1052c6ed0 <+44>: ldr x10, [x0, #0x48] 0x1052c6ed4 <+48>: cmp x10, #0x0 0x1052c6ed8 <+52>: csel x9, x9, x10, eq 0x1052c6edc <+56>: stp x9, x0, [sp, #0x10] 0x1052c6ee0 <+60>: adrp x9, 63 0x1052c6ee4 <+64>: add x9, x9, #0x9db ; "BUG IN CLIENT OF LIBDISPATCH: Assertion failed: " 0x1052c6ee8 <+68>: stp x9, x8, [sp] 0x1052c6eec <+72>: adrp x1, 63 0x1052c6ef0 <+76>: add x1, x1, #0x9a6 ; "%sBlock was %sexpected to execute on queue [%s (%p)]" 0x1052c6ef4 <+80>: sub x0, x29, #0x18 0x1052c6ef8 <+84>: bl 0x105301b18 ; symbol stub for: asprintf 0x1052c6efc <+88>: ldur x19, [x29, #-0x18] 0x1052c6f00 <+92>: str x19, [sp] 0x1052c6f04 <+96>: adrp x0, 63 0x1052c6f08 <+100>: add x0, x0, #0xa11 ; "%s" 0x1052c6f0c <+104>: bl 0x1052f9ef8 ; _dispatch_log 0x1052c6f10 <+108>: adrp x8, 95 0x1052c6f14 <+112>: str x19, [x8, #0x1f0] -> 0x1052c6f18 <+116>: brk #0x1 The app still crashes when I comment this code, and all Core Data related warnings. I'm quite stuck now as I want to use Swift 6. Has anyone figured CloudKit, CoreData and Swift 6 for sharing between users?
0
0
16
13h
[Mac] CloudKit CKQuerySubscription silent push notifications not arriving
I have the following code running on macOS and iOS: CKQuerySubscription *zsub = [[CKQuerySubscription alloc] initWithRecordType:ESS_CLOUDCONTROLLER_RECORDTYPE_PUSHNOTE predicate:[NSPredicate predicateWithFormat:@"TRUEPREDICATE"] subscriptionID:@"pushZSub" options:CKQuerySubscriptionOptionsFiresOnRecordUpdate|CKQuerySubscriptionOptionsFiresOnRecordCreation|CKQuerySubscriptionOptionsFiresOnRecordDeletion]; zsub.zoneID = zid; CKNotificationInfo *inf = [[CKNotificationInfo alloc] init]; inf.shouldSendContentAvailable = YES; inf.desiredKeys = @[ESS_PN_RECORDFIELD_KEY_OVERALLDATE]; zsub.notificationInfo = inf; CKModifySubscriptionsOperation *msop = [[CKModifySubscriptionsOperation alloc] initWithSubscriptionsToSave:@[zsub] subscriptionIDsToDelete:nil]; msop.qualityOfService = NSQualityOfServiceUserInitiated; msop.modifySubscriptionsCompletionBlock = ^(NSArray<CKSubscription *> * _Nullable savedSubscriptions, NSArray<CKSubscriptionID> * _Nullable deletedSubscriptionIDs, NSError * _Nullable operationError) { dispatch_async(dispatch_get_main_queue(), ^{ if (savedSubscriptions.count == 1) { //works also when already created. compH(YES, nil); } else { compH(NO, nil); } }); }; [self.database addOperation:msop]; (code synopsis: after i create a custom zone (not shown in code), I add a ckquerysubscription to it for a specific record type, configured as a silent notification) When I change the according record in my Mac app, I get an immediate silent push on iOS. On macOS, however, after I change the record in my iOS app, I don't get one. Sometimes, one silent push makes it through every now and then a minute+ late or so, and after that, it's going missing again. What's the deal? Everything's set up correctly (com.apple.developer.aps-environment is set, container-identifiers are the same, icloud services are the same, ubiquity-kvstore-identifier are the same). I obviously register for remote notifications in both apps. I see all the records and subscriptions and zones in both the Mac and iOS app. I tried setting alertBody to an empty string, or soundName to an empty string, or both to an empty string: no difference I tried having different subscriptions for my Mac and iOS app, since they use different bundle ids, but that was merged into one subscription server-side, so I'm thinking that's not it I tried making it not-silent by setting contentAvailable to NO and adding a full alertBody, title and subtitle. Again, worked on iOS, not on macOS. This has been going on since macOS 14 Sonoma (when I first got reports of this. Now running on macOS 26.3). Before Sonoma, it worked just fine. Now I thought perhaps it's because I had a subscription on the default zone, and not a custom one, so I tried subscribing to changes on a record in a custom zone (see code above), but that did not change anything either. It's all working fine, only the push notifications are not making it through to the Mac app. If I sudo killall apsd (kill the push service daemon), the last push notification suddenly miraculously makes it through, by the way. At this point, I'm out of ideas and would very much appreciate pointers as to how to debug this. Polling every 30 seconds for changes is so 1990s. Speaking of which, this is a rather long-time-running app (started in 2011). Could my CloudKit database be “too old” or “corrupted” or whatever? Thank you kindly, – Matthias
1
0
53
2d
Getting a list of deleted CloudKit records with an expired change token
Usually, when you call fetchRecordZoneChanges with the previous change token, you get a list of the record ID’s that have been deleted since your last fetch. But if you get a changeTokenExpired error because it‘s been too long since you last fetched, you have to call fetch again without a token. For my specific application, I still need to know, though, if any records have been deleted since my last sync. How can I get that information if I no longer have a valid change token?
7
0
405
2d
SwiftData + CloudKit: BGSystemTaskScheduler Code=8
Hi everyone, On macOS 26.4 beta (with Xcode 26.4 beta), I’m seeing the following console messages in a brand new SwiftData + CloudKit template project (no custom logic added, fresh CloudKit container): updateTaskRequest called for a pre-running task com.apple.coredata.cloudkit.activity.export.F9EE783D-7521-4EC2-B42C-9FD1F29BA5C4 updateTaskRequest called for an already running/updated task com.apple.coredata.cloudkit.activity.export.F9EE783D-7521-4EC2-B42C-9FD1F29BA5C4 Error updating background task request: Error Domain=BGSystemTaskSchedulerErrorDomain Code=8 "(null)" These messages appear: When CloudKit is enabled Occasionally on app launch Often when bringing the app back to the foreground (Cmd-Tab away and back) Even with zero additional SwiftData logic They do not appear when CloudKit is disabled. This behavior is reproducible on a completely new project with a fresh CloudKit container. Questions: What exactly do these messages indicate? Is BGSystemTaskScheduler Code=8 expected in this context? Are these safe to ignore? Is this a known change in logging behavior in macOS 26.4 beta? Additionally, in a larger project I’ve observed SwiftData crashes and initially suspected these logs might be related. However, since the issue reproduces in a fresh template project, I’m unsure whether this is simply verbose beta logging or something more serious. Any clarification would be appreciated. Filed as FB21993521.
2
0
64
2d
NSStagedMigrationManager Merging Steps
Hello, I have 3 model versions and I'm trying to step through migration. Version 2 makes significant changes to v1. As a result, I've renamed the entities in question by appending _v2 to their name, as the data isn't important to retain. v3, remove's the appended version number from v2. Setting the .xcdatamodeld to v3 and the migrations steps array as follows causes the app to error [ NSLightweightMigrationStage([v1]), NSLightweightMigrationStage([v2]), NSLightweightMigrationStage([v3]), ] CoreData: error: <NSPersistentStoreCoordinator: 0x10740d680>: Attempting recovery from error encountered during addPersistentStore: 0x10770f8a0 Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration." An error occurred during persistent store migration. Cannot merge multiple root entity source tables into one destination entity root table. I find this odd because if I run the migration independently across app launches, the migration appears to drop the no longer used tables in v2, then re-add them back in v3. So it seems to me that something is not finishing completely with the fully stepped through migration. -- I'm also unable to understand how to use NSCustomMigrationStage I've tried setting it to migrate from v1, to v2, but I'm getting a crash with error Duplicate version checksums across stages detected
4
0
163
6d
Does 'perform(schedule: .immediate)' guarantee serial execution?
If I have two consecutive calls like to perform(schedule: .immediate) like so: func doSomething() async { await self.perform(schedule: .immediate) { // add log event 1 to data store } await self.perform(schedule: .immediate) { // add log event 2 to data store } } Can I be guaranteed that the block for log event 1 will happen after log event 2? "log event" here is just an example, so please ignore things like storing date, etc. Looking at the documentation here: https://developer.apple.com/documentation/coredata/nsmanagedobjectcontext/perform(schedule:_:) It's a little unclear whether any such guarantee is in place. However, given that the function returns the value from the block, it seems like I should be able to expect event 1 will always be executed before event 2 regardless of the schedule parameter?
1
0
71
6d
macOS to macOS SwiftData iCloud Sync Problems
I am a novice developer, so please be kind. 😬 I am developing a simple macOS app backed with SwiftData and trying to set up iCloud sync so data syncs between two Macs running the app. I have added the iCloud capability, checked the CloudKit box, and selected an iCloud Container. Per suggestion of Paul Hudson, my model properties have either default values or are marked as optional, and the only relationship in my model is marked as optional. @Model final class Project { // Stable identifier used for restoring selected project across launches. var uuid: UUID? var name: String = "" var active: Bool = true var created: Date = Foundation.Date(timeIntervalSince1970: 0) var modified: Date = Foundation.Date(timeIntervalSince1970: 0) // CloudKit requires to-many relationships to be optional in this schema. @Relationship var timeEntries: [TimeEntry]? init(name: String, active: Bool = true, uuid: UUID? = UUID()) { self.uuid = uuid self.name = name self.active = active self.created = .now self.modified = .now self.timeEntries = [] } @Model final class TimeEntry { // Core timing fields. var start: Date = Foundation.Date(timeIntervalSince1970: 0) var end: Date = Foundation.Date(timeIntervalSince1970: 0) var codeRawValue: String? var activitiesRawValue: String = "" // Inverse relationship back to the owning project. @Relationship(inverse: \Project.timeEntries) var project: Project? init( start: Date = .now, end: Date = .now.addingTimeInterval(60 * 60), code: BillingCode? = nil, activities: [ActivityType] = [] ) { self.start = start self.end = end self.codeRawValue = code?.rawValue self.activitiesRawValue = Self.serializeActivities(activities) } I have set up the following in the AppDelegate for registering for remote notifications as well as some logging to console that the remote notification token was received and to be notified when when I am receiving remote notifications. private final class TimeTrackerAppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ notification: Notification) { print("📡 [Push] Registering for remote notifications") NSApplication.shared.registerForRemoteNotifications() } func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let tokenPreview = deviceToken.map { String(format: "%02x", $0) }.joined().prefix(16) print("✅ [Push] Registered for remote notifications (token prefix: \(tokenPreview)...)") } func application(_ application: NSApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { let nsError = error as NSError print("❌ [Push] Failed to register for remote notifications: \(nsError.domain) (\(nsError.code)) \(nsError.localizedDescription)") } func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String: Any]) { print("📬 [Push] Received remote notification: \(userInfo)") } } In testing, I run the same commit from Xcode on two different Macs logged into the same iCloud account. My problem is that sync is not reliably working. Starting up the app on both Macs shows that the app successfully registered for remote notifications. Sometimes, making an edit on Mac 1 is immediately reflected in Mac 2 UI along with didReceiveRemoteNotification message (all occurring while the Mac 2 app remains in foreground). Sometimes, the Mac 2 app needs to be backgrounded and re-foregrounded before the UI shows the updated data. Sometimes, an edit on Mac 2 will show on Mac 1 only after re-foregrounded but not show any didReceiveRemoteNotification on the Mac 1 console. Sometimes, an edit on Mac 2 will not show at all on Mac 1 even after re-foregrounding the app. Sometimes, no edits sync between either Mac. I had read about how a few years back, there was a bug in macOS where testing iCloud sync between Macs did not work while running from Xcode but would work in TestFlight. For me, running my app in TestFlight on both Macs has never been able to sync any edits between the Macs. Any idea where I might be going wrong. It seems this should not be this hard and should not be failing so inconsistently. Wondering what I might be doing wrong here.
4
0
79
1w
Finder tag colors and folder icons become gray for iCloud Drive items (URLResourceValues / xattr / QLThumbnailGenerator)
Hi, I’m working on a macOS app that includes a file browser component. And I’m trying to match Finder’s behavior for color tags and folder icons. For local files/folders everything works fine: Tag color key returns the expected label number via NSColor * labelColor = nil; [fileURL getResourceValue:&labelColor forKey:NSURLLabelColorKey error:nil]; NSNumber * labelKey = nil; [fileURL getResourceValue:&labelKey forKey:NSURLLabelNumberKey error:nil]; QLThumbnailGenerator obtains the expected colored folder icon (including emoji/symbol overlay if set) via QLThumbnailGenerationRequest * request = [[QLThumbnailGenerationRequest alloc] initWithFileAtURL:fileURL size:iconSize scale:scaleFactor representationTypes:QLThumbnailGenerationRequestRepresentationTypeIcon]; request.iconMode = YES; [[QLThumbnailGenerator sharedGenerator] generateBestRepresentationForRequest:request completionHandler:^(QLThumbnailRepresentation * _Nullable thumbnail, NSError * _Nullable error) { if (thumbnail != nil && error == nil) { NSImage * thumbnailImage = [thumbnail NSImage]; // ... } }]; However, for items on iCloud Drive (whether currently downloaded locally or only stored in the cloud), the same code always produces gray colors, while Finder shows everything correctly: NSURLLabelNumberKey always returns 1 (gray) for items with color tags, and 0 for non-tagged. Folder icons returned via QLThumbnailGenerator are gray, no emoji/symbol overlays. Reading tag data from xattr gives values like “Green\1” (tag name matches, but numeric value is still "Gray"). Also, if I move a correctly-tagged local item into iCloud Drive, it immediately becomes gray in my app (Finder still shows the correct colors). Question: What is the supported way to retrieve Finder tag colors and the correct folder icon appearance (color + overlays) for items in iCloud Drive, so that the result matches Finder? I am on macOS Tahoe 26.2/26.3, Xcode 26.2 (17C52). If you need any additional details, please let me know. Thanks!
2
0
77
1w
Which characters in filenames cause iCloud document sync issues?
Apple's iCloud File Management documentation says to "avoid special punctuation or other special characters" in filenames, but doesn't specify which characters. I need a definitive list to implement filename sanitization in my shipping app. Confirmed issues Our iOS app (CyberTuner, App Store, 15 years shipping on App Store) manages .rcta files in the iCloud ubiquity container via NSFileManager APIs. We've confirmed two characters causing sync failures: Ampersand (&): A file named Yamaha CP70 & CP80.rcta caused repeated "couldn't be backed up" dialogs. ~12 users reported this independently. Replacing & resolved it immediately. No other files in the same directory were affected. Percent (%): A file with % in the filename was duplicated by iCloud sync (e.g., filename% 1.rcta, filename% 2.rcta), and the original was lost. Currently reproducing across multiple devices. Both characters have special meaning in URL encoding (% is the escape character, & is the query parameter separator), which suggests the issue may be in URL handling within the sync pipeline. What I'm looking for: A definitive list of characters that cause problems in the iCloud sync pipeline specifically — not APFS restrictions, but CloudDocs/FileProvider/server-side issues. Confirmation whether these characters are problematic: & % # ? + / : * " < > | Is there a system API for validating or sanitizing filenames for iCloud compatibility before writing to the ubiquity container? Our users are piano technicians who naturally name files "Steinway & Sons" — we need to know exactly what to sanitize rather than guessing. Environment: iOS 17–26, Xcode 26.1, APFS, NSFileManager ubiquity container APIs Bundle FEEDBACK ASSISTANT ID FB21900837
0
0
57
1w
How to test CKShare across multiple accounts?
I'm testing CloudKit Sharing (CKShare) in my app. My app uses CloudKit Sharing to share private data between users (this is not App Store Family Sharing or purchase sharing, it's app-level sharing via CKShare). To properly test this, I need three or four Apple Accounts with distinct roles in my app. This means I need three/four separate iCloud accounts signed in on test devices. Simulators are probably ok: two acting as "parents" (share owner and participant): parent1.sandbox@example.com parent2.sandbox@example.com, one or two as a "child" (participant) child1.sandbox@example.com child2.sandbox@example.com except obviously using my domain name. I attempted to create Sandbox Apple Accounts in App Store Connect, but these don't appear to work with CloudKit Sharing. I then created several standard Apple Accounts, but I've now hit a limit — I believe my mobile number (used for two-factor authentication on the test accounts) has been flagged or rate-limited for account creation, and I can no longer create or verify new accounts with it. It's also blocked the email addresses associated with those accounts from being used for new account creation. Can Apple or anyone advise on the recommended approach for testing CloudKit Sharing with multiple participants? are Sandbox accounts supposed to work for CKShare, or do I need full Apple Accounts? How do i create and verify these in the correct way to avoid hitting these limits or breaking terms of service?
1
0
64
1w
CKShare(rootRecord:) Returns Share with Nil Root Even When All CloudKit Best Practices Followed (iOS 26.2.1)
I’m seeing an issue with CloudKit sharing in iOS 26.2.1: When I call CKShare(rootRecord:) with a brand-new record in a fresh custom zone, the share is created with no root attached (rootFromShare == nil). After saving both the root and share in a single CKModifyRecordsOperation, fetching the share from the server still shows no root reference (rootRecordID == nil). No errors are thrown, but sharing simply fails. Key facts: • Custom zone created and confirmed (sharing enabled, capsRaw=7/15) • Brand-new record type and fresh IDs each run • Never reusing records or shares • Saving both root and share together in one operation • No default zone usage; always custom private zone Tested: • Multiple devices, iCloud accounts, and app versions • Both simulator and physical device Debug logs consistently show: • SHARE_CREATE_SHARE_LOCAL ... rootFromShare=nil • After save/fetch: rootRecordID=nil on server Has anyone seen this? Is there a new CloudKit regression in iOS 26.x, or am I missing something subtle? Minimal sample project and full debug logs available if needed. Any insights or workarounds would be hugely appreciated!
1
0
144
1w
Bug? SwiftData + inheritance + optional many-to-one relationship
I've spent a few months writing an app that uses SwiftData with inheritance. Everything worked well until I tried adding CloudKit support. To do so, I had to make all relationships optional, which exposed what appears to be a bug. Note that this isn't a CloudKit issue -- it happens even when CloudKit is disabled -- but it's due to the requirement for optional relationships. In the code below, I get the following error on the second call to modelContext.save() when the button is clicked: Could not cast value of type 'SwiftData.PersistentIdentifier' (0x1ef510b68) to 'SimplePersistenceIdentifierTest.Computer' (0x1025884e0). I was surprised to find zero hit when Googling "Could not cast value of type 'SwiftData.PersistentIdentifier'". Some things to note: Calling teacher.computers?.append(computer) instead of computer.teacher = teacher results in the same error. It only happens when Teacher inherits Person. It only happens if modelContext.save() is called both times. It works if the first modelContext.save() is commented out. If the second modelContext.save()is commented out, the error occurs the second time the model context is saved (whether explicitly or implicitly). Keep in mind this is a super simple repro written to generate on demand the error I'm seeing in a normal app. In my app, modelContext.save() must be called in some places to update the UI immediately, sometimes resulting in the error seconds later when the model context is saved automatically. Not calling modelContext.save() doesn't appear to be an option. To be sure, I'm new to this ecosystem so I'd be thrilled if I've missed something obvious! Any thoughts are appreciated. import Foundation import SwiftData import SwiftUI struct ContentView: View { @Environment(\.modelContext) var modelContext var body: some View { VStack { Button("Do it") { let teacher = Teacher() let computer = Computer() modelContext.insert(teacher) modelContext.insert(computer) try! modelContext.save() computer.teacher = teacher try! modelContext.save() } } } } @Model class Computer { @Relationship(deleteRule: .nullify) var teacher: Teacher? init() {} } @Model class Person { init() {} } @available(iOS 26.0, macOS 26.0, *) @Model class Teacher: Person { @Relationship(deleteRule: .nullify, inverse: \Computer.teacher) public var computers: [Computer]? = [] override init() { super.init() } }
8
2
311
2w
CloudKit sync fails across TestFlight iOS + macOS builds — “Field recordName is not marked queryable”
I’m running into a CloudKit sync issue that I can’t reconcile after multiple rebuilds, TestFlight uploads, and entitlement verification, and I’m hoping for guidance on what I’m missing or whether this is expected behavior. Context App: RankSpinnah Platforms: iOS + macOS Distribution: TestFlight Xcode: 26.x Both apps use the same bundle identifier, same container, and same Apple Developer team Automatic signing enabled; Xcode-managed profiles CloudKit capability enabled for both targets Both builds install and run correctly from TestFlight on: iPhone 17 Pro Apple-silicon Mac (M5 MacBook Pro) The Problem CloudKit data does not sync at all between devices. On both iOS and macOS, CloudKit queries return no records, and I consistently see this error: Field 'recordName' is not marked queryable This occurs even when querying for records that should exist and after fresh installs on both devices. What I’ve Verified Same iCloud account signed in on both devices CloudKit container exists and is enabled App Sandbox enabled with network access CloudKit entitlements present in the signed app (verified from the archived .app) TestFlight builds are using the correct container Rebuilt and re-uploaded after version bump (1.2.0 / build 2026.02.03) Both iOS and macOS apps successfully uploaded and installed via TestFlight Despite this, no data syncs, and the queryable error persists. What I’m Unsure About Whether recordName is expected to be non-queryable in production schemas Whether TestFlight + CloudKit requires an explicit production schema deploy beyond what Xcode manages Whether this indicates a schema mismatch between development and production environments Or whether something subtle changed in recent Xcode / CloudKit behavior Ask Can someone clarify: Whether querying by recordName should work in production CloudKit What specifically causes the “Field recordName is not marked queryable” error in TestFlight builds What steps are required to ensure CloudKit schemas are correctly deployed for cross-platform sync At this point I feel like I’m missing one critical step, but I can’t identify what it is. Thanks in advance for any guidance.
1
0
116
2w
Read, Write, and Consuming Files / URLs
Hello, I have an asset pack that I'm use to periodically distribute a sqlite database thats being used to an NSPersistentStore. Because the database is over a few GBs, and the files in an AssetPack are not mutable, I have to stream the database into a temporary file, then replace my NSPersistentStore. This requires that the user has 3x the storage available of the database, and permanently uses twice to storage needed. I'd like: To be able to mark a URL/File to be accessible for read/write access To be able to mark a file / URL as consumed when it's no needed. So that it can be cleared from the user storage while still maintaining an active subscription to the asset pack for updates. Thank you
4
0
275
2w
CKSyncEngine initial sync on a new device
I have implemented CKSyncEngine synchronization, and it works well. I can update data on one device and see the changes propagate to another device quickly. However, the initial sync when a user downloads the app on a new device is a significant issue for both me and my users. One problem is that the sync engine fetches deletion events from the server. On a new device, the local database is empty, so these deletions are essentially no-ops. This would not be a big problem if there were only a few records or if it was fast. I measured the initial sync and found that there are 150 modified records and 62,168 deletions. Counting these alone takes over five minutes, even without processing them. The deletions do nothing because the local database has nothing to delete, yet they still add a significant delay. I understand that the sync engine ensures consistency across all devices, but five minutes of waiting with the app open just to insert a small number of records is excessive. The problem would be worse if there were tens of thousands of new records to insert, since downloading and saving the data would take even longer. This leads to a poor user experience. Users open the app and see data being populated for several minutes, or they are stuck on a screen that says the data is being synchronized with iCloud. I am wondering if there is a way to make the sync engine ignore deletion events when the state serialization is nil. Alternatively, is there a recommended method for handling initial synchronization more efficiently? One idea I considered is storing all the data as a backup in iCloud Documents, along with the state serialization at that point in time. When a user opens the app for the first time, I could download the file, extract the data, and set the state serialization to the saved value. I am not sure if this would work. I do not know if state serialization is tied to the device or if it only represents the point where the sync engine left off. My guess is that it might reference some local device storage. I am not sure what else to try. I could fetch all data using CloudKit, create the sync engine with an empty state serialization, and let it fetch everything again, but that would still take a long time. My records are very small, mostly a date when something happened and an ID referencing the parent. Since the app tracks watched episodes, I only store the date the user watched the episode and the ID of that episode.
4
0
266
2w
How to figure out sync errors in Production?
I'm using SwiftData with CloudKit private database. I was able to identify the error on my device by debugging in Xcode with com.apple.CoreData.SQLDebug flag. However, in Production, I couldn't find a way to get the cause of errors. I tried inspecting the error coming from eventChangedNotification. The NSPersistentCloudKitContainer.Event error does not contain any underlying error (neither CKError.userInfo nor in NSError.underlyingError). It only reports a partial failure with CKErrorDomain code 2. If a user encounter an error, there seems to be no way to retrieve the error details. Is there any way to access the error details or logs in Production?
1
0
181
3w
Asset Pack Limit
I have a total of 100 asset packs associated with my app but I have archived 5 of them. Unfortunately I am now unable to upload any more asset packs (the reported error is "backgroundAsset limit reached -- This app has already reached the maximum number of active backgroundAssets. Maximum allowed is 100.") I assumed that archiving asset packs would make them inactive (and thus not count against the limit). This seems to not be the case and I'm not sure how I can upload new asset packs.
4
0
236
3w
Naming Collision Between Model Attribute and Enum Case in SwiftData and CloudKit
There is a conflict in SwiftData (specifically when synced with CloudKit) when a @Model attribute shares the same name as a case within its assigned enum type. When this occurs, accessing the attribute on a model instance consistently returns the value corresponding to the enum case name, rather than the actual value persisted in the database. Steps to Reproduce Define an enumeration (e.g., Status) with a case that matches a planned property name (e.g., case status). Create a SwiftData @Model that uses this enum. Name the property in the model the same as the enum case. Attempt to save and then retrieve the value. Example Code enum TaskStatus: String, Codable { case status // The conflict source case pending case completed } @Model class TodoItem { // Conflict: Property name matches enum case name var status: TaskStatus init(status: TaskStatus) { self.status = status } } Expected Behavior The property item.status should return the value stored in the database (e.g., .pending or .completed). Actual Behavior The property item.status consistently resolves to the enum case .status, ignoring the actual persisted data.
1
0
84
3w
Provisioning profile missing entitlement
My iOS app uses CloudKit key-value storage. I have not updated the app in a few years but it works fine. Since it was last updated, I transferred the app from an old organization to my personal developer account. Now that I'm working on the app again I get an error: Provisioning profile "iOS Team Provisioning Profile: com.company.app" doesn't match the entitlements file's value for the com.apple.developer.ubiquity-kvstore-identifier entitlement. In the entitlement file, it has $(TeamIdentifierPrefix)$(CFBundleIdentifier) as the value for iCloud Key-Value Store. I've verified the variables resolve as expected. When I parse the provisioning profile there is no entitlement value for key-value storage. What am I getting wrong?
16
0
1.1k
3w