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

swift
Hi, thank you for your reply. I have checked and confirmed that all AppleUser entity fields (id, name, email, password, createdAt) are optional, relationships (posts, comments) are optional, and I assign values when creating a new object, but Core Data still throws a nilError during registration; I have uploaded my project to GitHub for your reference here: https://github.com/Kawiichao/job. If reviewing it requires any payment, please let me know in advance. Thank you very much for your kind offer—I really appreciate it!
1
0
56
Sep ’25
Default zone is not accessible in shared DB - cloudKit
I am trying to save to cloud kit shared database. The shared database does not allow zones to be set up. How do I save to sharedCloudDatabase without a zone? private func addItem(recordType: String, name: String) { let record = CKRecord(recordType: recordType) record[Constances.field.name] = name as CKRecordValue record[Constances.field.done] = false as CKRecordValue record[Constances.field.priority] = 0 as CKRecordValue CKContainer.default().sharedCloudDatabase.save(record) { [weak self] returnRecord, error in if let error = error { print("Error saving record: \(record[Constances.field.name] as? String ?? "No Name"): \n \(error)") return } } } The following error message prints out: Error saving record: Milk: <CKError 0x15af87900: "Server Rejected Request" (15/2027); server message = "Default zone is not accessible in shared DB"; op = B085F7BA703D4A08; uuid = 87AEFB09-4386-4E43-81D7-971AAE8BA9E0; container ID = "iCloud.com.sfw-consulting.Family-List">
1
0
68
Jun ’25
How to get a real time and date (not device time) for query?
I need to know the current date to query CloudKit data with it, like: let predicate = NSPredicate(format: "publishedAt <= %@", currentDateAndTime) I don't need high precision, even +/- a few minutes is fine, but I can't rely on device's time since the user can manually change it. Researching this myself I see that the most reliable method is to get the date from the server. There are NTP servers, but accessing them requires additional libraries which adds complexity. TrueTime (last updated 6 years ago) and Kronos (updated like once a year) seem outdated, given how much Swift has changed in the past years. I can make an HTTP request to a website like Google or Apple and read the current time from its headers. But I don't know if this method is reliable. I know I can create a dummy record in CloudKit, update it, and read its modificationDate. But it feels hacky. Maybe there is another way to fetch the current date directly from CloudKit? It feels like it should be easy and there is a straightforward solution, but I just can't find it.
1
0
586
Jan ’25
CKSyncEngine: Duplicate FetchedRecordZoneChanges & Sync Handling Questions
Hi everyone, I've recently implemented CKSyncEngine in my app, and I have two questions regarding its behavior: Duplicate FetchedRecordZoneChanges After Sending Changes: I’ve noticed that the engine sometimes receives a FetchedRecordZoneChanges event containing modifications and deletions that were just sent by the same device a few moments earlier. This event arrives after the SentRecordZoneChanges event, and both events share the same recordChangeTag, which results in double-handling the record. Is this expected behavior? I’d like to confirm if this is how CKSyncEngine works or if I might be overlooking something. Handling Initial Sync with a "Sync Screen": When a user opens the app for the first time and already has data stored in iCloud, I need to display a "Sync Screen" temporarily to prevent showing partial data or triggering abrupt, rapid UI changes. I’ve found that canceling current operations, then awaiting sendChanges() and fetchChanges() works well to ensure data is fully synced before dismissing the sync screen: displaySyncScreen = true await syncEngine.cancelOperations() try await syncEngine.sendChanges() try await syncEngine.fetchChanges() displaySyncScreen = false However, I’m unsure if canceling operations like this could lead to data loss or other issues. Is this a safe approach, or would you recommend a better strategy for handling this initial sync state?
1
0
613
Feb ’25
Is there a guaranteed order for records in CKSyncEngine's handleFetchedRecordZoneChanges?
I have two recordTypes in CloudKit: Author and Book. The Book records have their parent property set to an Author, enabling hierarchical record sharing (i.e., if an Author record is shared, the participant can see all books associated with that author in their shared database). When syncing with CKSyncEngine, I was expecting handleFetchedRecordZoneChanges to deliver all Author records before their associated Book records. However, unless I’m missing something, the order appears to be random. This randomness forces me to handle two codepaths in my app (opposed to just one) to replicate CloudKit references in my local persistency storage: Book arrives before its Author → I store the Book but defer setting its parent reference until the corresponding Author arrives. Author arrives before its Books → I can immediately set the parent reference when each Book arrives. Is there a way to ensure that Author records always arrive before Book records when syncing with CKSyncEngine? Or is this behavior inherently unordered and I have to implement two codepaths?
1
0
617
Feb ’25
Error accessing backing data on deleted item in detached task
I have been working on an app for the past few months, and one issue that I have encountered a few times is an error where quick subsequent deletions cause issues with detached tasks that are triggered from some user actions. Inside a Task.detached, I am building an isolated model context, querying for LineItems, then iterating over those items. The crash happens when accessing a Transaction property through a relationship. var byTransactionId: [UUID: [LineItem]] { return Dictionary(grouping: self) { item in item.transaction?.id ?? UUID() } } In this case, the transaction has been deleted, but the relationship existed when the fetch occurred, so the transaction value is non-nil. The crash occurs when accessing the id. This is the error. SwiftData/BackingData.swift:1035: Fatal error: This model instance was invalidated because its backing data could no longer be found the store. PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(backing: SwiftData.PersistentIdentifier.PersistentIdentifierBacking.managedObjectID(0xb43fea2c4bc3b3f5 &lt;x-coredata://A9EFB8E3-CB47-48B2-A7C4-6EEA25D27E2E/Transaction/p1756&gt;))) I see other posts about this error and am exploring some suggestions, but if anyone has any thoughts, they would be appreciated.
1
0
146
Oct ’25
Inheritance in SwiftData — Fatal error: Never access a full future backing data
I'm implementing SwiftData with inheritance in an app. I have an Entity class with a property name. This class is inherited by two other classes: Store and Person. The Entity model has a one-to-many relationship with a Transaction class. I can list all my Entity models in a List with a @Query annotation without a problem. However, then I try to access the name property of an Entity from a Transaction relationship, the app crashes with the following error: Thread 1: Fatal error: Never access a full future backing data - PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(backing: SwiftData.PersistentIdentifier.PersistentIdentifierBacking.managedObjectID(0x96530ce28d41eb63 <x-coredata://DABFF7BB-C412-474E-AD50-A1F30AC6DBE9/Person/p4>))) with Optional(F07E7E23-F8F0-4CC0-B282-270B5EDDC7F3) From my attempts to fix the issue, I noticed that: The crash seems related to the relationships with classes that has inherit from another class, since it only happens there. When I create new data, I can usually access it without any problem. The crash mostly happens after reloading the app. This error has been mentioned on the forum (for example here), but in a context not related with inheritance. You can find the full code here. For reference, my models looks like this: @Model class Transaction { @Attribute(.unique) var id: String var name: String var date: Date var amount: Double var entity: Entity? var store: Store? { entity as? Store } var person: Person? { entity as? Person } init( id: String = UUID().uuidString, name: String, amount: Double, date: Date = .now, entity: Entity? = nil, ) { self.id = id self.name = name self.amount = amount self.date = date self.entity = entity } } @Model class Entity: Identifiable { @Attribute(.preserveValueOnDeletion) var name: String var lastUsedAt: Date @Relationship(deleteRule: .cascade, inverse: \Transaction.entity) var operations: [Transaction] init( name: String, lastUsedAt: Date = .now, operations: [Transaction] = [], ) { self.name = name self.lastUsedAt = lastUsedAt self.operations = operations } } @available(iOS 26, *) @Model class Store: Entity { @Attribute(.unique) var id: String var locations: [Location] init( id: String = UUID().uuidString, name: String, lastUsedAt: Date = .now, locations: [Location] = [], operations: [Transaction] = [] ) { self.locations = locations self.id = id super.init(name: name, lastUsedAt: lastUsedAt, operations: operations) } } In order to reproduce the error: Run the app in the simulator. Click the + button to create a new transaction. Relaunch the app, then click on any transaction. The app crashes when it tries to read te name property while building the details view.
1
0
219
Sep ’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 - CKContainer.m:747 error
Hi everyone, Complete newbie here. Building an app and trying to use Cloudkit. I've added the CloudKit capability, triple checked the entitlements file for appropriate keys, made sure the code signing entitlements are pointing to the correct entitlements file. I've removed and cleared all of those settings and even created a new container as well as refreshed the signing. I just can't seem to figure out why I keep getting this error: Significant issue at CKContainer.m:747: In order to use CloudKit, your process must have a com.apple.developer.icloud-services entitlement. The value of this entitlement must be an array that includes the string "CloudKit" or "CloudKit-Anonymous". Any guidance is greatly appreciated.
1
0
111
Sep ’25
Multible saved accounts and SwiftData
For a CRM application, I want users to be able to switch between accounts and have their saved contacts stored locally. Whenever a user logs in, the app should fetch data from their specific database location. What’s the best practice to achieve this? Should I create a separate database for each user? Should I store all the data in one database and filter it by user? Or is there a better approach I should consider?
1
0
105
Mar ’25
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
Nested method calls in `context.perform` with Swift 6
I'm calling a method with the context as parameter, within the context's perform block – is this really not legal in Swift 6? actor MyActor { func bar(context: NSManagedObjectContext) { /* some code */ } func foo(context: NSManagedObjectContext) { context.performAndWait { self.bar(context: context) // WARN: Sending 'context' risks causing data races; this is an error in the Swift 6 language mode // 'self'-isolated 'context' is captured by a actor-isolated closure. actor-isolated uses in closure may race against later nonisolated uses // Access can happen concurrently } } } The warning appears when I call a method with a context parameter, within the performAndWait-block. Background: In my app I have methods that takes in API data, and I need to call the same methods from multiple places with the same context to store it, and I do not want to copy paste the code and have hundreds of lines of duplicate code. Is there a well-known "this is how you should do it" for situations like this? This is related to a previous post I made, but it's a bit flimsy and got no response: https://developer.apple.com/forums/thread/770605
1
1
859
Feb ’25
Is iCloud sync working?
Hello, I tried to validate if my app was properly syncing to the cloud. To test this, I created some data in the app, and then deleted the app, and reinstalled. I was expecting the data to still exist but it isn't. Is this a valid test or is the data expected to be deleted when app is deleted?
1
0
172
Mar ’25
SwiftData property marked ephemeral getting persisted in CloudKit
Am I misunderstanding the expected behavior here, or is there a bug in the behavior of @Attribute(.ephemeral) tagged SwiftData model properties? The documentation for .ephemeral says "Track changes to this property but do not persist". I started using .ephemeral because @Transient was inhibiting SwiftUI from reacting to changes to the property through @Observable. I am updating the value of my @Attribute(.ephemeral) property about once a second and I am seeing corresponding console log output showing the property as part of the generated CKRecord object. I then confirmed in the CloudKit dev portal that the .ephemeral property was added to the Record schema and contains real values. The behavior seems as though the .ephemeral property is being completely ignored. This is observed in a new Xcode project using SwiftData with CloudKit, Xcode 16.2, macOS 15.3.1 and during Build & Run testing on physical devices.
1
0
686
Feb ’25
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
SwiftData + CloudKit causes watchOS app termination during WKExtendedRuntimeSession (FB17685611)
Hi all, I’m encountering a consistent issue with SwiftData on watchOS when using CloudKit sync. After enabling: let config = ModelConfiguration(schema: schema, cloudKitDatabase: .automatic) …the app terminates ~30–60 seconds into a WKExtendedRuntimeSession. This happens specifically when: Always-On Display is OFF The iPhone is disconnected or in Airplane Mode The app is running in a WKExtendedRuntimeSession (e.g., used for meditation tracking) The Xcode logs show a warning: Background Task ("CoreData: CloudKit Setup"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. It appears CloudKit sync setup is being triggered automatically and flagged by the system as an unmanaged long-running task, leading to termination. Workaround: Switching to: let config = ModelConfiguration(schema: schema, cloudKitDatabase: .none) …prevents the issue entirely — no background task warning, no crash. Feedback ID submitted: FB17685611 Just wanted to check if others have seen this behavior or found alternative solutions. It seems like something Apple may need to address in SwiftData’s CloudKit handling on watchOS.
1
1
183
May ’25
@Query with Set
How do I filter data using @Query with a Set of DateComponents? I successfully saved multiple dates using a MultiDatePicker in AddView.swift. In ListView.swift, I want to retrieve all records for the current or today’s date. There are hundreds of examples using @Query with strings and dates, but I haven’t found an example of @Query using a Set of DateComponents Nothing will compile and after hundreds and hundreds of attempts, my hair is turning gray. Please, please, please help me. For example, if the current date is Tuesday, March 4 205, then I want to retrieve both records. Since both records contain Tuesday, March 4, then retrieve both records. Sorting works fine because the order by clause uses period which is a Double. Unfortunately, my syntax is incorrect and I don’t know the correct predicate syntax for @Query and a Set of DateComponents. Class Planner.swift file import SwiftUI import SwiftData 
 @Model class Planner { //var id: UUID = UUID() var grade: Double = 4.0 var kumi: Double = 4.0 var period: Double = 1.0 var dates: Set<DateComponents> = [] init( grade: Double = 4.0, kumi: Double = 4.0, period: Double = 1.0, dates: Set<DateComponents> = [] ) { self.grade = grade self.kumi = kumi self.period = period self.dates = dates 
 } } @Query Model snippet of code does not work The compile error is to use a Set of DateComponents, not just DateComponents. @Query(filter: #Predicate<Planner> { $0.dates = DateComponents(calendar: Calendar.current, year: 2025, month: 3, day: 4)}, sort: [SortDescriptor(\Planner.period)]) var planner: [Planner] ListView.swift image EditView.swift for record #1 DB Browser for SQLlite: record #1 (March 6, 2025 and March 4, 2025) 
 
 [{"isLeapMonth":false,"year":2025,"day":6,"month":3,"calendar":{"identifier":"gregorian","minimumDaysInFirstWeek":1,"current":1,"locale":{"identifier":"en_JP","current":1},"firstWeekday":1,"timeZone":{"identifier":"Asia\/Tokyo"}},"era":1},{"month":3,"year":2025,"day":4,"isLeapMonth":false,"era":1,"calendar":{"locale":{"identifier":"en_JP","current":1},"timeZone":{"identifier":"Asia\/Tokyo"},"current":1,"identifier":"gregorian","firstWeekday":1,"minimumDaysInFirstWeek":1}}]
 EditView.swift for record #2 DB Browser for SQLlite: record #2 (March 3, 2025 and March 4, 2025) 
 [{"calendar":{"minimumDaysInFirstWeek":1,"locale":{"current":1,"identifier":"en_JP"},"timeZone":{"identifier":"Asia\/Tokyo"},"firstWeekday":1,"current":1,"identifier":"gregorian"},"month":3,"day":3,"isLeapMonth":false,"year":2025,"era":1},{"year":2025,"month":3,"era":1,"day":4,"isLeapMonth":false,"calendar":{"identifier":"gregorian","current":1,"firstWeekday":1,"minimumDaysInFirstWeek":1,"timeZone":{"identifier":"Asia\/Tokyo"},"locale":{"current":1,"identifier":"en_JP"}}}]
 
 Any help is greatly appreciated.
1
0
81
Mar ’25