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

CloudKit CKRecordZone Deletion Issue
CloudKit CKRecordZone Deletion Issue Problem: CloudKit record zones deleted via CKDatabase.modifyRecordZones(deleting:) or CKModifyRecordZonesOperation are successfully removed but then reappear. I suspect they are automatically reinstated by CloudKit sync, despite successful deletion confirmation. Environment: SwiftData with CloudKit integration Custom CloudKit zones created for legacy zone-based sharing Observed Behavior: Create custom zone (e.g., "TestZone1") via CKDatabase.modifyRecordZones(saving:) Copy records to zone for sharing purposes Delete zone using any CloudKit deletion API - returns success, no errors Immediate verification: Zone is gone from database.allRecordZones() After SwiftData/CloudKit sync or app restart: Zone reappears Reproduction: Tested with three different deletion methods - all exhibit same behaviour: modifyRecordZones(deleting:) async API CKModifyRecordZonesOperation (fire-and-forget) CKModifyRecordZonesOperation with result callbacks Zone deletion succeeds, change tokens (used to track updates to shared records) cleaned up But zones are restored presumably by CloudKit background sync Expected: Deleted zones should remain deleted Actual: Zones are reinstated, creating orphaned zones
0
0
6
3h
SwiftData with CloudKit Sync Issue
I am using SwiftData with CloudKit to synchronize data across multiple devices, and I have encountered an issue: occasionally, abnormal sync behavior occurs between two devices (it does not happen 100% of the time—only some users have reported this problem). It seems as if synchronization between the two devices completely stops; no matter what operations are performed on one end, the other end shows no response. After investigating, I suspect the issue might be caused by both devices simultaneously modifying the same field, which could lead to CloudKit's logic being unable to handle such conflicts and causing the sync to stall. Are there any methods to avoid or resolve this situation? Of course, I’m not entirely sure if this is the root cause. Has anyone encountered a similar issue?
0
0
50
4d
SwiftData crash when enabling CloudKit for existing users (Free to Pro upgrade)
Hi, I am implementing a premium feature in my app where CloudKit syncing is available only for "Pro" users. The Workflow: Free Users: I initialize the ModelContainer with cloudKitDatabase: .none so their data stays local. Pro Upgrade: When a user purchases a subscription, I restart the container with cloudKitDatabase: .automatic to enable syncing. The Problem: If a user starts as "Free" (creates local data) and later upgrades to "Pro", the app crashes immediately upon launch with the following error: Fatal error: Failed to create ModelContainer: SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer, _explanation: nil) It seems that SwiftData fails to load the existing data once the configuration changes to expect a CloudKit-backed store. My Question: Is there a supported way to "toggle" CloudKit on for an existing local dataset without causing this crash? I want the user's existing local data to start syncing once they pay, but currently, it just crashes. My code: import Foundation import SwiftData public enum DataModelEnum: String { case task, calendar public static let container: ModelContainer = { let isSyncEnabled = UserDefaults.isProUser let config = ModelConfiguration( groupContainer: .identifier("group.com.yourcompany.myApp"), cloudKitDatabase: isSyncEnabled ? .automatic : .none ) do { return try ModelContainer(for: TaskModel.self, CalendarModel.self, configurations: config) } catch { fatalError("Failed to create ModelContainer: \(error)") } }() }
1
0
57
6d
iCloud Container Cannot Enable in Xcode — App ID Won’t Accept Container / Missing iCloud Documents Toggle
Hi everyone, I am experiencing an iCloud provisioning problem I cannot resolve, and Developer Support has not been able to help. My App ID: com.exaqservices.ArkyvTiles Symptoms: 1. In Xcode (v16.2), enabling iCloud in Signing & Capabilities repeatedly fails with: The app ID does not include the iCloud container. Click Try Again. Clicking Try Again does nothing. The error persists forever. 2. In Certificates, Identifiers & Profiles: • The iCloud capability is enabled for this App ID. • The CloudKit container is selected. • But the portal no longer shows the “iCloud Documents” checkbox, which used to be required for ubiquitous document support. 3. Xcode cannot regenerate provisioning profiles because it claims the App ID is missing the iCloud container — even though the container is attached. 4. Provisioning profiles on the Apple Developer site all appear expired, and new ones do not generate correctly. 5. The App Store Connect interface also does not show an iCloud Services section under App Information → Capabilities as older guides describe. Expected Behavior: Since iCloud and the CloudKit container are enabled on the App ID, Xcode should successfully enable: • com.apple.developer.icloud-services • com.apple.developer.icloud-container-identifiers • com.apple.developer.ubiquity-container-identifiers (if needed) • com.apple.developer.ubiquity-kvstore-identifier Instead, the entitlements never propagate. What I suspect: This seems like an App ID metadata mismatch or a stale backend entry where: • the CloudKit container is attached but the entitlement isn’t linked, • the “iCloud Documents” flag is missing due to a UI transition, • provisioning profiles cannot be regenerated because the App ID is not updating correctly. What I need help with: Can someone from Apple engineering confirm: • Whether my App ID metadata is corrupted, • If entitlements need to be manually refreshed, • Or if the “iCloud Documents” toggle has moved or is no longer exposed? This is blocking development completely — I cannot build, sign, or deploy the app with iCloud. Thank you! Alan Metzger
1
0
41
1w
iCloud Database Errors and Limits
We are currently implementing a custom iCloud sync for our macOS and iOS apps using CloudKit. Syncing works fine as long as the number of record sends is relatively small. But when we test with a large number of changes ( 80,000+ CKRecords ) we start running into problems. Our sending strategy is very conservative to avoid rate limits: We send records sequentially in batches of 250 records With about 2 seconds pause between operations Records are small and contain no assets (assets are uploaded separately) At some point we start receiving: “Database commit size exceeds limit” After that, CloudKit begins returning rate-limit errors with retryAfter-Information in the error. We wait for the retry time and try again, but from this moment on, nothing progresses anymore. Every subsequent attempt fails. We could not find anything in the official documentation regarding such a “commit size” limit or what triggers this failure state. So my questions are: Are there undocumented limits on the total number of records that can exist in an iCloud database (private or shared)? Is there a maximum volume of record modifications a container can accept within a certain timeframe, even if operations are split into small batches with pauses? Is it possible that sending large numbers of records in a row can temporarily or permanently “stall” a CloudKit container? Any insights or experiences would be greatly appreciated. Thank you!
0
0
111
1w
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 <x-coredata://A9EFB8E3-CB47-48B2-A7C4-6EEA25D27E2E/Transaction/p1756>))) I see other posts about this error and am exploring some suggestions, but if anyone has any thoughts, they would be appreciated.
2
0
208
1w
Container Failing to Initialize After a Successful Migration & Initialization
I'm experiencing the following error with my SwiftData container when running a build: Code=134504 "Cannot use staged migration with an unknown model version." Code Structure - Summary I am using a versionedSchema to store multiple models in SwiftData. I started experiencing this issue when adding two new models in the newest Schema version. Starting from the current public version, V4.4.6, there are two migrations. Migration Summary The first migration is to V4.4.7. This is a lightweight migration removing one attribute from one of the models. This was tested and worked successfully. The second migration is to V5.0.0. This is a custom migration adding two new models, and instantiating instances of the two new models based on data from instances of the existing models. In the initial testing of this version, no issues were observed. Issue and Steps to Reproduce Reproduction of issue: Starting from a fresh build of the publicly released V4.4.6, I run a new build that contains both Schema Versions (V4.4.7 and V5.0.0), and their associated migration stages. This builds successfully, and the container successfully migrates to V5.0.0. Checking the default.store file, all values appear to migrate and instantiate correctly. The second step in reproduction of the issue is to simply stop running the build, and then rebuild, without any code changes. This fails to initialize the model container every time afterwards. Going back to the simulator after successive builds are stopped in Xcode, the app launches and accesses/modifies the model container as normal. Supplementary Issue: I have been putting up with the same, persistent issue in the Xcode Preview Canvas of "Failed to Initialize Model Container" This is a 5 in 6 build issue, where builds will work at random. In the case of previews, I have cleared all data associated with all previews multiple times. The only difference being that the simulator is a 100% failure rate after the initial, successful initialization. I assume this is due to the different build structure of previews. Lastly, of note, the Xcode previews fail at the same line in instantiating the model container as the simulator does. From my research into this issue, people say that the Xcode preview is instantiating from elsewhere. I do have a separate model container set up specifically for canvas previews, but the error does not occur in that container, but rather the app's main container. Possible Contributing Factors & Tested Facts iOS: While I have experienced issues with SwiftData and the complier in iOS 26, I can rule that out as the issue here. This has been tested on simulators running iOS 18.6, 26.0.1, and 26.1, all encountering failures to initialize model container. While in iOS 18, subsequent builds after the successful migration did work, I did eventually encounter the same error and crash. In iOS 26.0.1 and 26.1, these errors come immediately on the second build. Container Initialization for V4.4.6 do { container = try ModelContainer( for: Job.self, JobTask.self, Day.self, Charge.self, Material.self, Person.self, TaskCategory.self, Service.self, migrationPlan: JobifyMigrationPlan.self ) } catch { fatalError("Failed to Initialize Model Container") } Versioned Schema Instance for V4.4.6 (V4.4.7 differs only by versionIdentifier) static var versionIdentifier = Schema.Version(4, 4, 6) static var models: [any PersistentModel.Type] { [Job.self, JobTask.self, Day.self, Charge.self, Material.self, Person.self, TaskCategory.self, Service.self] } Container Initialization for V5.0.0 do { let schema = Schema([Jobify.self, JobTask.self, Day.self, Charge.self, MaterialItem.self, Person.self, TaskCategory.self, Service.self, ServiceJob.self, RecurerRule.self]) container = try ModelContainer( for: schema, migrationPlan: JobifyMigrationPlan.self ) } catch { fatalError("Failed to Initialize Model Container") } Versioned Schema Instance for V5.0.0 static var versionIdentifier = Schema.Version(5, 0, 0) static var models: [any PersistentModel.Type] { [ JobifySchemaV500.Job.self, JobifySchemaV500.JobTask.self, JobifySchemaV500.Day.self, JobifySchemaV500.Charge.self, JobifySchemaV500.Material.self, JobifySchemaV500.Person.self, JobifySchemaV500.TaskCategory.self, JobifySchemaV500.Service.self, JobifySchemaV500.ServiceJob.self, JobifySchemaV500.RecurerRule.self ] } Addressing Differences in Object Names Type-aliasing: All my model types are type-aliased for simplification in view components. All types are aliased as 'JobifySchemeV446.<#Name#>' in V.4.4.6, and 'JobifySchemaV500.<#Name#>' in V5.0.0 Issues with iOS 26: My type-aliases dating back to iOS 17 overlapped with lower level objects in Swift, including 'Job' and 'Material'. These started to be an issue with initializing the model container when running in iOS 26. The type aliases have been renamed since, however the V4.4.6 build with the old names runs and builds perfectly fine in iOS 26 If there is any other code that may be relevant in determining where this error is occurring, I would be happy to add it. My current best theory is simply that I have mistakenly omitted code relevant to the SwiftData Migration.
2
0
548
1w
Best approach to prevent SwiftData .transformable migration on iOS 26.1
We have an unreleased SwiftData app for iOS18+. While we were testing I saw reports on the forum about unexpected database migrations for codable arrays on iOS26.1. I'd like to ask a couple of questions: 1- Does this issue originate from the new Xcode version, or is it specific to iOS 26.1? 2- Is it possible to change our attribute so that users on older iOS versions receive the same model, preventing a migration from being triggered when they upgrade to iOS 26.1? One of our models looks like this: struct Point: Codable, Hashable { let x: Int let y: Int } @Model class Grid { private(set) var gridId: String = "" var points: [Point] = [] var updatedAt: Date = Date() private(set) var createdAt: Date = Date() #Index<Grid>([\.gridId]) ... } I can think of some options like: // 1 @Attribute(.transformable(by: CustomJsonTransformer.self)) var points: [Point] = [] // 2 @Attribute(.externalStorage) var points: [Point] = [] // 3 var points: Data = Data() // store points as data However, I'm not sure which one to use. What would you recommend to handle this, or is there a better strategy you would suggest?
0
0
84
1w
Xcode 26.1 / OS 26.1 regression with schema and macros
After Xcode 26.1 was updated and installing the OS 26.1 simulators, my app started crashing related to transformable properties. When I checked my schema, I noticed that properties with array collection types are suddenly set with an option transformable with Optional("NSSecureUnarchiveFromData")], even though I do not use any transformable types. I verified the macros, no transformable was specified. This is causing ModelCoders to encode/decode my properties incorrectly. This is not an issue when I switch back to OS 26.0 simulators.
4
0
209
1w
SwiftUI Sheet view with @Query loses model context
I've run into a strange issue. If a sheet loads a view that has a SwiftData @Query, and there is an if statement in the view body, I get the following error when running an iOS targetted SwiftUI app under MacOS 26.1: Set a .modelContext in view's environment to use Query While the view actually ends up loading the correct data, before it does, it ends up re-creating the sqlite store (opening as /dev/null). The strange thing is that this only happens if there is an if statement in the body. The statement need not ever evaluate true, but it causes the issue. Here's an example. It's based on the default xcode new iOS project w/ SwiftData: struct ContentView: View { @State private var isShowingSheet = false var body: some View { Button(action: { isShowingSheet.toggle() }) { Text("Show Sheet") } .sheet(isPresented: $isShowingSheet, onDismiss: didDismiss) { VStack { ContentSheetView() } } } func didDismiss() { } } struct ContentSheetView: View { @Environment(\.modelContext) private var modelContext @Query public var items: [Item] @State var fault: Bool = false var body: some View { VStack { if fault { Text("Fault!") } Button(action: addItem) { Label("Add Item", systemImage: "plus") } List { ForEach(items) { item in Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard)) } } } } private func addItem() { withAnimation { let newItem = Item(timestamp: Date()) modelContext.insert(newItem) } } } It requires some data to be added to trigger, but after adding it and dismissing the sheet, opening up the sheet with trigger the Set a .modelContext in view's environment to use Query. Flipping on -com.apple.CoreData.SQLDebug 1 will show it trying to recreate the database. If you remove the if fault { Text("Fault!") } line, it goes away. It also doesn't appear to happen on iPhones or in the iPhone simulator. Explicitly passing modelContext to the ContentSheetView like ContentSheetView().modelContext(modelContext) also seems to fix it. Is this behavior expected?
2
0
158
2w
SwiftData: This model instance was invalidated because its backing data could no longer be found the store
Hello 👋, I encounter the "This model instance was invalidated because its backing data could no longer be found the store" crash with SwiftData. Which from what I understood means I try to access a model after it has been removed from the store (makes sense). I made a quick sample to reproduce/better understand because there some case(s) I can't figure it out. Let's take a concrete example, we have Home model and a Home can have many Room(s). // Sample code @MainActor let foo = Foo() // A single reference let database = Database(modelContainer: sharedModelContainer) // A single reference @MainActor class Foo { // Properties to explicilty keep reference of model(s) for the purpose of the POC var _homes = [Home]() var _rooms = [Room]() func fetch() async { let homes = await database.fetch().map { sharedModelContainer.mainContext.model(for: $0) as! Home } print(ObjectIdentifier(homes[0]), homes[0].rooms?.map(\.id)) // This will crash here or not. } // Same version of a delete function with subtle changes. // Depending on the one you use calling delete then fetch will result in a crash or not. // Keep a reference to only homes == NO CRASH func deleteV1() async { self._homes = await database.fetch().map { sharedModelContainer.mainContext.model(for: $0) as! Home } await database.delete() } // Keep a reference to only rooms == NO CRASH func deleteV2() async { self._rooms = await database.fetch().map { sharedModelContainer.mainContext.model(for: $0) as! Home }[0].rooms ?? [] await database.delete() } // Keep a reference to homes & rooms == CRASH 💥 func deleteV3() async { self._homes = await database.fetch().map { sharedModelContainer.mainContext.model(for: $0) as! Home } self._rooms = _homes[0].rooms ?? [] // or even only retain reference to rooms that have NOT been deleted 🤔 like here "id: 2" make it crash // self._rooms = _homes[0].rooms?.filter { r in r.id == "2" } ?? [] await database.delete() } } Calling deleteV() then fetch() will result in a crash or not depending on the scenario. I guess I understand deleteV1, deleteV2. In those case an unsaved model is served by the model(for:) API and accessing properties later on will resolve correctly. The doc says: "The identified persistent model, if known to the context; otherwise, an unsaved model with its persistentModelID property set to persistentModelID." But I'm not sure about deleteV3. It seems the ModelContext is kind of "aware" there is still cyclic reference between my models that are retained in my code so it will serve these instances instead when calling model(for:) API ? I see my home still have 4 rooms (instead of 2). So I then try to access rooms that are deleted and it crash. Why of that ? I mean why not returning home with two room like in deleteV1 ? Because SwiftData heavily rely on CoreData may be I miss a very simple thing here. If someone read this and have a clue for me I would be extremely graceful. PS: If someone wants to run it on his machine here's some helpful code: // Database let sharedModelContainer: ModelContainer = { let schema = Schema([ Home.self, Room.self, ]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) debugPrint(modelConfiguration.url.absoluteString.replacing("%20", with: "\\ ")) return try! ModelContainer(for: schema, configurations: [modelConfiguration]) }() extension Database { static let shared = Database(modelContainer: sharedModelContainer) } @ModelActor actor Database { func insert() async { let r1 = Room(id: "1", name: "R1") let r2 = Room(id: "2", name: "R2") let r3 = Room(id: "3", name: "R3") let r4 = Room(id: "4", name: "R4") let home = Home(id: "1", name: "My Home") home.rooms = [r1, r2, r3, r4] modelContext.insert(home) try! modelContext.save() } func fetch() async -> [PersistentIdentifier] { try! modelContext.fetchIdentifiers(FetchDescriptor<Home>()) } @MainActor func delete() async { let mainContext = sharedModelContainer.mainContext try! mainContext.delete( model: Room.self, where: #Predicate { r in r.id == "1" || r.id == "4" } ) try! mainContext.save() // 🤔 Calling fetch here seems to solve crash too, force home relationship to be rebuild correctly ? // let _ = try! sharedModelContainer.mainContext.fetch(FetchDescriptor<Home>()) } } // Models @Model class Home: Identifiable { @Attribute(.unique) public var id: String var name: String @Relationship(deleteRule: .cascade, inverse: \Room.home) var rooms: [Room]? init(id: String, name: String, rooms: [Room]? = nil) { self.id = id self.name = name self.rooms = rooms } } @Model class Room: Identifiable { @Attribute(.unique) public var id: String var name: String var home: Home? init(id: String, name: String, home: Home? = nil) { self.id = id self.name = name self.home = home } }
2
0
156
2w
Saving a file to ubiquitous storage overwrites iCloud version without conflict
Our app saves its data to iCloud by default. In most cases, this is working as intended & the data can be synced across devices with no problems. But recently, in testing, we discovered a situation where it's possible to save data before the NSMetadataQuery finishes & starts downloading the cloud files. When this happens, the query will then finish, and return the NEW file (with no other versions or conflicts). Is there a way to ensure that writing a file (version A) to ubiquitous storage when another version (version B) exists in the cloud is treated as a conflict, rather than just stomping all over the other version? I've tried querying the file metadata for the file URL (NSURLIsUbiquitousItemKey, NSMetadataUbiquitousItemDownloadingStatusKey, NSURLUbiquitousItemDownloadRequestedKey, NSURLUbiquitousItemHasUnresolvedConflictsKey) before saving, but it just returns nil.
0
0
84
2w
CloudKit Dashboard completely empty (no containers at all) while Xcode 26 still shows my production container iCloud.gainzCloud and builds fine – Tahoe 26.1 / Xcode 26.0 (17A321)
Hi, I’m completely stuck with a very strange CloudKit problem that started recently and has now killed all iCloud sync for a live production app. What is happening Production container: iCloud.gainzCloud (created ~11 months ago, has been working perfectly until now) In Xcode 26.0 (17A321): → Signing & Capabilities → iCloud is enabled → Container correctly shows as iCloud.gainzCloud → App builds and runs on device/simulator with zero provisioning or container errors CloudKit Dashboard (https://icloud.developer.apple.com/dashboard/): completely blank – “No containers found” Result: CloudKit sync is dead for every user (development + production environments) What I know for sure Apple Developer Support confirmed the container iCloud.gainzCloud still exists and is correctly attached to my Team ID on their backend Personal iCloud (Mail, Notes, Photos, etc.) syncs perfectly on the same Mac / same Apple ID under macOS Tahoe 26.1 I have NOT changed the password on either the Apple ID or the Developer Program account New containers I create appear in Xcode but never show up in the Dashboard Environment macOS Tahoe 26.1 (latest) Xcode Version 26.0 (17A321) Has anyone on the new Tahoe/Xcode 26 releases seen the CloudKit Dashboard suddenly go completely empty while Xcode still “sees” the container just fine? Any known trick to force the dashboard to re-index containers or clear whatever cache is broken? Thanks a lot in advance – this is blocking all iCloud functionality for a released app with active users.
0
0
28
2w
SwiftData not loading under iOS 26.1
Updated the phone to iOS 26.1 and now the app is not working anymore, even previously approved version published on App Store which works perfectly on iOS 26.0.1, and iOS 18+. I deleted the app from the phone and installed fresh from App Store, still the same. Logic is that on start app copies previously prepared SwiftData store file (using the same models) from app bundle to Documents directory and uses it. Currently app just hungs with loader spinner spinning as it can t connect to the store. Getting this error in console when running from Xcode on real device with iOS 26.1 installed: CoreData: error: CoreData: error: Store failed to load. <NSPersistentStoreDescription: 0x10c599e90> (type: SQLite, url: file:///var/mobile/Containers/Data/Application/DA32188D-8887-48F7-B828-1F676C8FBEF8/Documents/default.store) with error = Error Domain=NSCocoaErrorDomain Code=134140 "Persistent store migration failed, missing mapping model." UserInfo={sourceModel=(<NSManagedObjectModel: 0x10c503ac0>) isEditable 0, entities { /// there goes some long models description addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134140) Any help or workaround will be greatly appreciated.
8
0
512
2w
CK WebServices getting 500 Internal Error
Hello, If I want to modify records in my public database, this works fine. However, if I change from public to private in the requesturl, I get the response: "500 - Internal Error". According to the CK WebService Reference, it is possible to access the private database. Could someone explain to me if it is really an internal error and if it could be fixed by Apple, since I would like to access my own private database with the server-to-server key. Thanks in advance.
1
0
59
2w