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

Stopping certain data models from syncing to cloudkit
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?
0
0
76
Apr ’25
CloudKit sync stopped working with error „You can't save and delete the same record"
Hi there We're using CloudKit in our app which, generally, syncs data perfectly between devices. However, recently the sync has stopped working (some changes will never sync and the sync is delayed for several days even with the app open on all devices). CloudKit's logs show the error „You can't save and delete the same record" and „Already have a mirrored relationship registered for this key", etc. We’ve a hunch that this issue is related to a mirrored relationship of one database entity. Our scenario: We've subclassed the database entities. The database model (which we can't share publicly) contains mirrored relationships. We store very long texts in the database (similar to a Word document that contains markup data – in case that’s relevant). Deleting all data and starting with a completely new container and bundle identifier didn’t help (we tried that multiple times). This issue occurs on macOS (15.2(24C101) as well on iOS (18.2). Any hints on how to get the sync working again? Should we simply avoid mirrored relationships? Many thanks
3
0
765
Jan ’25
iCloud Drive changes in iOS 18.4 and later break stated API
The NSMetadataUbiquitousItemDownloadingStatusKey indicates the status of a ubiquitous (iCloud Drive) file. A key value of NSMetadataUbiquitousItemDownloadingStatusDownloaded is defined as indicating there is a local version of this file available. The most current version will get downloaded as soon as possible . However this no longer occurs since iOS 18.4. A ubiquitous file may remain in the NSMetadataUbiquitousItemDownloadingStatusDownloaded state for an indefinite period. There is a workaround: call [NSFileManager startDownloadingUbiquitousItemAtURL: error:] however this shouldn't be necessary, and introduces delays over the previous behaviour. Has anyone else seen this behaviour? Is this a permanent change? FB17662379
0
0
87
May ’25
Debugging/Fixing deleted relationship objects with SwiftData
Using SwiftData and this is the simplest example I could boil down: @Model final class Item { var timestamp: Date var tag: Tag? init(timestamp: Date) { self.timestamp = timestamp } } @Model final class Tag { var timestamp: Date init(timestamp: Date) { self.timestamp = timestamp } } Notice Tag has no reference to Item. So if I create a bunch of items and set their Tag. Later on I add the ability to delete a Tag. Since I haven't added inverse relationship Item now references a tag that no longer exists so so I get these types of errors: SwiftData/BackingData.swift:875: Fatal error: This model instance was invalidated because its backing data could no longer be found the store. PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://EEC1D410-F87E-4F1F-B82D-8F2153A0B23C/Tag/p1), implementation: SwiftData.PersistentIdentifierImplementation) I think I understand now that I just need to add the item reference to Tag and SwiftData will nullify all Item references to that tag when a Tag is deleted. But, the damage is already done. How can I iterate through all Items that referenced a deleted tag and set them to nil or to a placeholder Tag? Or how can I catch that error and fix it when it comes up? The crash doesn't occur when loading an Item, only when accessing item.tag?.timestamp, in fact, item.tag?.id is still ok and doesn't crash since it doesn't have to load the backing data. I've tried things like just looping through all items and setting tag to nil, but saving the model context fails because somewhere in there it still tries to validate the old value. Thanks!
2
0
344
Mar ’25
SwiftData shared across apps?
The stuff I've found by searching has confused me, so hopefully someone can help simplify it for me? I have an app (I use it for logging which books I've given away), and I could either add a bunch of things to the app, or I could have another app (possibly a CLI tool) to generate some reports I'd like.
0
0
60
May ’25
Can't batch delete with one-to-many to self relationship
I have a simple model that contains a one-to-many relationship to itself to represent a simple tree structure. It is set to cascade deletes so deleting the parent node deletes the children. Unfortunately I get an error when I try to batch delete. A test demonstrates: @Model final class TreeNode { var parent: TreeNode? @Relationship(deleteRule: .cascade, inverse: \TreeNode.parent) var children: [TreeNode] = [] init(parent: TreeNode? = nil) { self.parent = parent } } func testBatchDelete() throws { let config = ModelConfiguration(isStoredInMemoryOnly: true) let container = try ModelContainer(for: TreeNode.self, configurations: config) let context = ModelContext(container) context.autosaveEnabled = false let root = TreeNode() context.insert(root) for _ in 0..<10 { let child = TreeNode(parent: root) context.insert(child) } try context.save() // fails if first item doesn't have a nil parent, succeeds otherwise // which row is first is random, so will succeed sometimes try context.delete(model: TreeNode.self) } The error raised is: CoreData: error: Unhandled opt lock error from executeBatchDeleteRequest Constraint trigger violation: Batch delete failed due to mandatory OTO nullify inverse on TreeNode/parent and userInfo { NSExceptionOmitCallstacks = 1; NSLocalizedFailureReason = "Constraint trigger violation: Batch delete failed due to mandatory OTO nullify inverse on TreeNode/parent"; "_NSCoreDataOptimisticLockingFailureConflictsKey" = ( ); } Interestingly, if the first record when doing an unsorted query happens to be the parent node, it works correctly, so the above unit test will actually work sometimes. Now, this can be "solved" by changing the reverse relationship to an optional like so: @Relationship(deleteRule: .cascade, inverse: \TreeNode.parent) var children: [TreeNode]? The above delete will work fine. However, this causes issues with predicates that test counts in children, like for instance deleting only nodes where children is empty for example: try context.delete(model: TreeNode.self, where: #Predicate { $0.children?.isEmpty ?? true }) It ends up crashing and dumps a stacktrace to the console with: An uncaught exception was raised Keypath containing KVC aggregate where there shouldn't be one; failed to handle children.@count (the stacktrace is quite long and deep in CoreData's NSSQLGenerator) Does anyone know how to work around this?
5
0
810
Jan ’25
NSPersistentCloudKitContainer not saving 50% of the time
I'm using NSPersistentCloudKitContainer to save, edit, and delete items, but it only works half of the time. When I delete an item and terminate the app and repoen, sometimes the item is still there and sometimes it isn't. The operations are simple enough: moc.delete(thing) try? moc.save() Here is my DataController. I'm happy to provide more info as needed class DataController: ObservableObject { let container: NSPersistentCloudKitContainer @Published var moc: NSManagedObjectContext init() { container = NSPersistentCloudKitContainer(name: "AppName") container.loadPersistentStores { description, error in if let error = error { print("Core Data failed to load: \(error.localizedDescription)") } } #if DEBUG do { try container.initializeCloudKitSchema(options: []) } catch { print("Error initializing CloudKit schema: \(error.localizedDescription)") } #endif moc = container.viewContext } }
2
0
370
Jan ’25
Display name for CloudKit container in the "Manage Storage" view of Settings
How can I set the display name of the CloudKit container in Settings -> iCloud -> Manage Storage. I have multiple containers, some legacy, and some for certain modules that are shared among a suite of apps. The problem is all Containers show the same name so it is not possible to advise a user which containers are safe to delete. I am using NSPersistentCloudKitContainer.
1
0
278
Nov ’24
Unable to see data from a production environment
I am trying to test using Testflight and have set up a test with a user on an account I also own which is different to me developer account. The app I believe is running in production on a separate device and is working from a user point of view, however I am not able to query the data via the console. As I said I know the user id and password as tey are mine so even when I use the Act as user service it logs in but the query is empty. I'm assuming I'm not doing anything wrong its possibly an security issue that is preventing me accessing this account. My question to the group then is how do I verify the data that is being tested?
1
0
605
Feb ’25
Avoiding deletion of referenced records
Let's say I have a CloudKit database schema where I have records of type Author that are referenced by multiple records of type Article. I want to delete an Author record if no Article is referencing it. Now consider the following conflict: device A deleted the last Article referencing Author #42 device B uploads a new Article referencing Author #42 at the same time The result should be that Author #42 is not deleted after both operations are finished. But both device don't know from each other changes. So either device B could miss that device A deleted the author. Or device A could have missed that a new Article was uploaded and therefore the Author #42 was deleted right after the upload of device B. I though about using a reference count first. But this won't work if the ref count is part of the Author record. This is because deletions do not use the changeTag to detect lost updates: If device A found a reference count 0 and decides to delete the Author, it might miss that device B incremented the count meanwhile. I currently see two alternatives: Using a second record that outlives the Author to keep the reference count and using an atomic operation to update and delete it. So if the update fails, the delete would fail either. Always adding a new child record to the Author whenever a reference is made. We could call it ReferenceToken. Since child records may not become dangling, CloudKit would stop a deletion, if a new ReferenceToken sets the parent reference to the Author. Are there any better ways doing this?
0
0
433
Nov ’24
NSPersistentCloudKitContainer uploads only a subset of records to public database in production environment
I'm having some issues where only a subset of records appear in CloudKit dashboard after I have saved some records in my iOS app using NSPersistentCloudKitContainer. I have noticed that when I'm running my app using the development environment of my CloudKit container everything works smoothly and is uploaded as expected but when I'm using the production environment only a subset of records are actually uploaded. I'm pulling my hair on how to debug this. -com.apple.CoreData.CloudKitDebug and -com.apple.CoreData.SQLDebug pukes out too much info in the console for me to pinpoint any issue.
1
0
664
Feb ’25
SiftData with CloudKit testing
I'm trying to add Cloud Kit integration to SwiftData app (that is already in the App Store, btw). When the app is installed on devices that are directly connected to Xcode, it works (a bit slow, but pretty well). But when the app is distributed to Testflight internal testers, the synchronization doesn't happen at all. So, is this situation normal and how can I test apps with iCloud integration properly?
2
0
357
Nov ’24
Records or Fields are Missing or Corrupt in Users Private CloudKit Databases (Recent Changes to CloudKit?)
Hi all, I've contacted Apple about this privately but I wanted to post this publicly too just to see if anyone else is experiencing the same issue. We use CloudKit to store "documents" (we'll call them) for our users. We use it directly, not via CoreData etc but through the lower level APIs. This has been working great for the last 9 months or so. Since a few days ago we've started receiving reports from users that their data has disappeared without a trace from their app. Obviously this is very serious and severe for us. We keep a local copy of the users data but if CloudKit tells us this data has been deleted we remove that local copy to keep in sync. Nothing has changed client side in terms of our code, and the only way we can see that could cause this, is a fetch that we perform asking for a list of the users "documents" is returning no rows/results, or possibly returning rows with invalid or missing fields. We have about 30,000 active users per day (1.5m requests/day) using CloudKit and we have only a handful of reports of this. Again this only started happening this week after 9 months of good service. Has anyone else noticed anything "strange" lately, fetches returning empty? fields missing? Is anyone at Apple aware of any recent changes to CloudKit? or outages? We're really unsure how or who should handle this and who we can escalate to? Any help appreciated. We have a workaround/mitigation on the way through review at the moment but this is a really big problem for us if we can't rely on CloudKit to remember users data reliably.
1
0
597
Feb ’25
Odd, transient .badContainer error in CloudKit
I'm beta-testing a CloudKit-based app. One of my testers suddenly reported that they got a .badContainer CloudKit error: <CKError 0x302619800:"Bad Container" (5/1014); server message = "Invalid container to get bundle ids"; op = <...>; uuid = <...>; container ID = "<...>"> (all private info replaced with <...>) The container ID in the message was exactly what I expected, and exactly what other users are successfully using. When I followed up on the report, the user said she tried again later and everything was fine. It's still working fine days later. What could cause a user to get a .badContainer message, when all other users using the same app are fine, the container ID makes sense, and future runs work fine? Is this something I need to worry about? Does it maybe sometimes happen when CloudKit is having some kind of outage?
1
0
653
Jan ’25
SwiftData Migration: Objects Created in Custom Migration Aren't Persisted or Queryable
Description: I'm experiencing a critical issue with SwiftData custom migrations where objects created during migration appear to be inserted successfully but aren't persisted or found by queries after migration completes. The migration logs show objects being created, but subsequent queries return zero results. Problem Details: I'm migrating from schema version V2 to V3, which involves: Renaming Person class to GroupData Keeping the same data structure but changing the class name Using a custom migration stage to copy data from old to new schema Migration Code: swift static let migrationV2toV3 = MigrationStage.custom( fromVersion: LinkMapV2.self, toVersion: LinkMapV3.self, willMigrate: { context in do { let persons = try context.fetch(FetchDescriptor<LinkMapV2.Person>()) print("Found (persons.count) Person objects to migrate") // ✅ Shows 11 objects for person in persons { let newGroup = LinkMapV3.GroupData( id: person.id, // Same UUID name: person.name, // ... other properties ) context.insert(newGroup) print("Inserted GroupData: '\(newGroup.name)'") // ✅ Confirms insertion } try context.save() // ✅ No error thrown print("Successfully migrated \(persons.count) objects") // ✅ Confirms save } catch { print("Migration error: \(error)") } }, didMigrate: { context in do { let groups = try context.fetch(FetchDescriptor<LinkMapV3.GroupData>()) print("Final GroupData count: \(groups.count)") // ❌ Shows 0 objects! } catch { print("Verification error: \(error)") } } ) Console Output: text === MIGRATION STARTED === Found 11 Person objects to migrate Migrating Person: 'Riverside of pipewall' with ID: 7A08C633-4467-4F52-AF0B-579545BA88D0 Inserted new GroupData: 'Riverside of pipewall' ... (all 11 objects processed) ... === MIGRATION COMPLETED === Successfully migrated 11 Person objects to GroupData === MIGRATION VERIFICATION === New GroupData count: 0 // ❌ PROBLEM: No objects found! What I've Tried: Multiple context approaches: Using the provided migration context Creating a new background context with ModelContext(context.container) Using context.performAndWait for thread safety Different save strategies: Calling try context.save() after insertions Letting SwiftData handle saving automatically Multiple save calls at different points Verification methods: Checking in didMigrate closure Checking in app's ContentView after migration completes Using both @Query and manual FetchDescriptor Schema variations: Direct V2→V3 migration Intermediate V2.5 schema with both classes Lightweight migration with @Attribute(originalName:) Current Behavior: Migration runs without errors Objects appear to be inserted successfully context.save() completes without throwing errors But queries in didMigrate and post-migration return empty results The objects seem to exist in a temporary state that doesn't persist Expected Behavior: Objects created during migration should be persisted and queryable Post-migration queries should return the migrated objects Data should be available in the main app after migration completes Environment: Xcode 16.0+ iOS 18.0+ SwiftData Swift 6.0+ Key Questions: Is there a specific way migration contexts should be handled for data to persist? Are there known issues with object persistence in custom migrations? Should we be using a different approach for class renaming migrations? Is there a way to verify that objects are actually being written to the persistent store? The migration appears to work perfectly until the verification step, where all created objects seem to vanish. Any guidance would be greatly appreciated! Additional Context from my investigation: I've noticed these warning messages during migration that might be relevant: text SwiftData.ModelContext: Unbinding from the main queue. This context was instantiated on the main queue but is being used off it. error: Persistent History (76) has to be truncated due to the following entities being removed: (Person) This suggests there might be threading or context lifecycle issues affecting persistence. Let me know if you need any additional information about my setup or migration configuration!
1
0
67
2d
CloudKit + SwifData setup
Hey folks, I'm having an issue where iCloud sync is only working in the Development environment, not on Prod. I have deployed the schema to Prod through the CloudKit console, although I did it after the app went live on the AppStore. Even though the two schema are identical, iCloud sync just doesn't work on Prod. Things I tried on the code side: Initially I did the most basic SwiftData+CloudKit setup: var modelContainer: ModelContainer { let schema = Schema([Book.self, Goal.self]) let config = ModelConfiguration(isStoredInMemoryOnly: false, cloudKitDatabase: doesUserSyncToiCloud ? .automatic : .none) var container: ModelContainer do { container = try ModelContainer(for: schema, configurations: config) } catch { fatalError() } return container } var body: some Scene { WindowGroup { AnimatedSplashScreen { MainTabView() } } .modelContainer(modelContainer) } This is enough to make iCloud sync work at the Development level. Then when I noticed the issues on Prod I did some digging and found this on the Docs (https://developer.apple.com/documentation/swiftdata/syncing-model-data-across-a-persons-devices): let config = ModelConfiguration() do { #if DEBUG // Use an autorelease pool to make sure Swift deallocates the persistent // container before setting up the SwiftData stack. try autoreleasepool { let desc = NSPersistentStoreDescription(url: config.url) let opts = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.example.Trips") desc.cloudKitContainerOptions = opts // Load the store synchronously so it completes before initializing the // CloudKit schema. desc.shouldAddStoreAsynchronously = false if let mom = NSManagedObjectModel.makeManagedObjectModel(for: [Trip.self, Accommodation.self]) { let container = NSPersistentCloudKitContainer(name: "Trips", managedObjectModel: mom) container.persistentStoreDescriptions = [desc] container.loadPersistentStores {_, err in if let err { fatalError(err.localizedDescription) } } // Initialize the CloudKit schema after the store finishes loading. try container.initializeCloudKitSchema() // Remove and unload the store from the persistent container. if let store = container.persistentStoreCoordinator.persistentStores.first { try container.persistentStoreCoordinator.remove(store) } } } #endif modelContainer = try ModelContainer(for: Trip.self, Accommodation.self, configurations: config) } catch { fatalError(error.localizedDescription) } I've no idea why Apple would include this CoreData setup in a SwiftData documentation, but I went ahead and adapted it to my code as well. I see now that some new "assets" were added to my Development schema, but I'm afraid to deploy these changes to Prod, since I'm not even confident that this CoreData setup is necessary in a SwiftData app. Does anyone have any thoughts on this? Have you run into similar issues? Any help would be much appreciated; thanks!
0
0
366
Nov ’24
How to Delete Tips from CloudKit?
Hi! I use Tips with CloudKit and it works very well, however when a user want to remove their data from CloudKit, how to do that? In CoreData with CloudKit area, NSPersistentCloudKitContainer have purgeObjectsAndRecordsInZone to delete both local managed objects and CloudKit records, however there is no information about the TipKit deletion. Does anyone know ideas?
2
0
396
Mar ’25
Strange behavior with 100k+ records in NSPersistentCloudKitContainer
I have been using the basic NSPersistentContainer with 100k+ records for a while now with no issues. The database size can fluctuate a bit but on average it takes up about 22mb on device. When I switch the container to NSPersistentCloudKitContainer, I see a massive increase in size to ~150mb initially. As the sync engine uploads records to iCloud it has ballooned to over 600mb on device. On top of that, the user's iCloud usage in settings reports that it takes up 1.7gb in the cloud. I understand new tables are added and history tracking is enabled but the size increase seems a bit drastic. I'm not sure how we got from 22mb to 1.7gb with the exact same data. A few other things that are important to note: I import all the 100k+ records at once when testing the different containers. At the time of the initial import there is only 1 relation (an import group record) that all the records are attached to. I save the background context only once after all the records and the import group have been made and added to the context. After the initial import, some of these records may have a few new relations added to them over time. I suppose this could be causing some of the size increase, but its only about 20,000 records that are updated. None of the records include files/ large binary data. Most of the attributes are encrypted. I'm syncing to the dev iCloud environment. When I do make a change to a single attribute in a record, CloudKit reports that every attribute has been modified (not sure if this is normal or not ) Also, When syncing to a new device, the sync can take hours - days. I'm guessing it's having to sync both the new records and the changes, but it exponentially gets slower as more records are downloaded. The console will show syncing activity, but new records are being added at a slower rate as more records are added. After about 50k records, it grinds to a halt and while the console still shows sync activity, only about 100 records are added every hour. All this to say i'm very confused where these issues are coming from. I'm sure its a combination of how i've setup my code and the vast record count, record history, etc. If anyone has any ideas it would be much appreciated.
2
0
586
Nov ’24
SwiftData - disable Persistent History Tracking
Hello, I am building a pretty large database (~40MB) to be used in my SwiftData iOS app as read-only. While inserting and updating the data, I noticed a substantial increase in size (+ ~10MB). A little digging pointed to ACHANGE and ATRANSACTION tables that apparently are dealing with Persistent History Tracking. While I do appreciate the benefits of that, I prefer to save space. Could you please point me in the right direction?
0
0
73
Apr ’25