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

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.
1
0
29
18h
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
153
3d
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
56
3d
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
62
6d
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
70
6d
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
44
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
51
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
134
1w
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?
6
0
382
2w
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
294
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
107
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
265
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
252
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
165
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
228
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
80
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
Unable to sync SwiftData model fully using CloudKit
Hey everyone I just ran into an issue where I couldn't sync the model below fully by using CloudKit, enum LinkMapV3_1: VersionedSchema { static let versionIdentifier: Schema.Version = .init(3, 1, 0) static var models: [any PersistentModel.Type] { [AnnotationData.self, GroupData.self, Item.self, Deployment.self, History.self] } // MARK: - Data @Model class AnnotationData { var name: String = "" var longitude: Double = 0.0 var latitude: Double = 0.0 var order: Int = -1 var level: Int = 1 var detail: String = "" @Relationship(deleteRule: .nullify, inverse: \GroupData.annotation) var groups: [GroupData]? @Relationship(deleteRule: .nullify, inverse: \AnnotationData.to) var from: AnnotationData? var to: AnnotationData? var history: History? } // MARK: - History @Model class History { var id: UUID = UUID() var timestamp: Date = Date() @Relationship(deleteRule: .nullify, inverse: \AnnotationData.history) var annotations: [AnnotationData]? @Relationship(deleteRule: .nullify, inverse: \GroupData.history) var groups: [GroupData]? @Relationship(deleteRule: .nullify, inverse: \Item.history) var items: [Item]? @Relationship(deleteRule: .nullify, inverse: \Deployment.history) var deployment: Deployment? var formattedDate: String { let formatter = DateFormatter() formatter.dateStyle = .medium formatter.timeStyle = .short return formatter.string(from: timestamp) } var timeAgo: String { let formatter = RelativeDateTimeFormatter() formatter.unitsStyle = .abbreviated return formatter.localizedString(for: timestamp, relativeTo: Date()) } } } So when trying to sync with the code in documentation let modelContainer: ModelContainer init() { let config = ModelConfiguration() typealias vs = LinkMapV3_1 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.name.Endsunset.LinkMap.SwiftData.v1") desc.cloudKitContainerOptions = opts // Load the store synchronously so it completes before initializing the // CloudKit schema. desc.shouldAddStoreAsynchronously = false if let mom = NSManagedObjectModel.makeManagedObjectModel(for: [vs.AnnotationData.self, vs.GroupData.self, vs.Item.self, vs.Deployment.self, vs.History.self]) { let container = NSPersistentCloudKitContainer(name: "LinkMap", 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: vs.AnnotationData.self, vs.GroupData.self, vs.Item.self, vs.Deployment.self, vs.History.self, configurations: config) } catch { fatalError(error.localizedDescription) } } The output is Console Output Where you can see Output Extract Optional arrays with @Relationship are missing, and the entry of record types on cloudkit database container are also missing it. When I attempt to insert an annotation, I got SwiftData/PersistentModel.swift:559: Fatal error: This KeyPath does not appear to relate AnnotationData to anything - \AnnotationData.groups It gets more suspicious when restart the app and try again, the above error end with "AnnotationData.history", and if I tried again the above error end with "AnnotationData.from"... and so on. No matter how my app stop working.
1
0
263
4w
@ComputedProperty vs copying values SwiftData AppEntity
I'm setting up App Entities for my SwiftData models and I'm not sure about the best way to reference SwiftData model properties in the AppEntity. I have a SwiftData model with many properties: @Model final class Contact { @Attribute(.unique) var id: UUID = UUID() var name: String var phoneNumber: String var email: String var website: URL? var birthday: Date? var notes: String // ... many more properties } I want to expose these properties on my AppEntity so they're available for system features, such as giving Apple Intelligence more context about on-screen content. struct ContactEntity: AppEntity { var id: UUID @Property(title: "Name") var name: String @Property(title: "Phone") var phoneNumber: String @Property(title: "Email") var email: String // ... all the other properties } I couldn't find guidance in the documentation for this specific situation. I've considered two approaches: Add @Property variables to the AppEntity for each SwiftData model property and copy all values from the SwiftData model to the AppEntity in the AppEntity initializer — but I recall this being discouraged in previous WWDC sessions since it duplicates data and can become stale Use @ComputedProperty to fetch the model and access the single properties — this seems like an alternative, but fetching the entire model just to access individual properties doesn't feel right What is the recommended approach when SwiftData is the data source? Thank you!
1
0
130
4w
Deleting Production Database SwiftData
Hi all, I have setup my app to use SwiftData with CloudKit sync. I have a production environment and development environment. I can reset the development environment for myself and all users in CloudKit console, but I can't reset the production one as it's tried to users' iCloud accounts, so I've added a button in-app for that feature. In the onboarding of my app, I pre-seed the DB with some default objects, which should be persisted between app install. The issue I'm running into is that I'm unable to force-pull these models from iCloud during the onboarding of a clean re-install, which leads to the models later appearing as duplicates once the user has been on the app for a few minutes and it has pulled from their iCloud account. If anyone has any suggestions on how to handle this issue, I would greatly appreciate it.
2
0
238
Jan ’26