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

Which distinct logic does FetchRequest use with "returnsDistinctResults"?
If I use <FetchRequest.returnsDistinctResults> with unique "identifier" property, and there happened to be multiple NSManagedObjects in Core Data that contains the same "identifier", does the FetchRequest retrieve the latest modified/created object? Is there a way to define the <FetchRequest.returnsDistinctResults> logic to be based on another property (e.g. "creationDate" / "modifiedDate") and the ascension order?
1
0
204
3w
SwiftData Inheritance Query Specialized Model
Hi, I am currently experiencing some trouble when using parent model property in a predicate of a child model. I have an Item class that define parent-child relationship: @Model class Item { var timestamp: Date @Relationship(inverse: \Item.children) var parent: Item? var children: [Item] init(parent: Item? = nil, children: [Item] = [], timestamp: Date = .now) { self.parent = parent self.children = children self.timestamp = timestamp } } I subclass this model like that: @available(iOS 26, *) @Model final class CollectionItem: Item { /* ... */ } When i make a Query in my View like that the system crashes: @Query( filter: #Predicate<CollectionItem> { $0.parent == nil }, sort: \CollectionItem.name, ) private var collections: [CollectionItem] CrashReportError: Fatal Error in DataUtilities.swift AppName crashed due to fatalError in DataUtilities.swift at line 85. Couldn't find \CollectionItem.<computed 0x000000034005d4e8 (Optional<Item>)> on CollectionItem with fields [SwiftData.Schema.PropertyMetadata(name: "name", keypath: \CollectionItem.<computed 0x000000034003c120 (String)>, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "icon", keypath: \CollectionItem.<computed 0x000000034003ca04 (Optional<String>)>, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "timestamp", keypath: \Item.<computed 0x0000000340048018 (Date)>, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "parent", keypath: \Item.<computed 0x0000000340048a4c (Optional<Item>)>, defaultValue: nil, metadata: Optional(Relationship - name: , options: [], valueType: Any, destination: , inverseName: nil, inverseKeypath: Optional(\Item.<computed 0x0000000340048fe8 (Array<Item>)>))), SwiftData.Schema.PropertyMetadata(name: "children", keypath: \Item.<computed 0x0000000340048fe8 (Array<Item>)>, defaultValue: nil, metadata: nil)] When I query as Item it works but then i cannot sort on CollectionItem field and must add unnecessary down casting: @Query( filter: #Predicate<Item> { $0.parent == nil && $0 is CollectionItem }, ) private var items: [Item] Am I missing something? Is it a platform limitation or a known issue?
9
0
231
3w
SwiftData and CloudKit
Recently I've been working on a demo project called iLibrary. The main goal was to learn more about CloudKit and SwiftData. After a while I noticed that there were some hangs/freezes when running the app in debug mode. I first tried this with Xcode 15.4 and iOS 17.5. Here the hang only appears at the beginning, but only for a few seconds. But when I exit debug mode, there are no more hangs. With Xcode 16 beta 4 and iOS 18 it looks completely different. In this case, the hangs and freezes are always present, whether in debug mode or not. And it's not just at the beginning, it's throughout the app. I'm aware that this is still a beta, but I still find this weird. And when I profile this I see that the main thread gets quite overloaded. Interestingly, my app doesn't have that many operations going on. So I guess something with the sync of SwiftData or my CloudKitManger where I fetch some records from the public database is not running fine. Lastly, I wanted to delete the iCloud app data. So I went to Settings and tried to delete it, but it didn't work. Is this normal? Does anyone have any idea what this could be? Or has anyone encountered this problem as well? I'd appreciate any support. My project: https://github.com/romanindermuehle/iLibrary
9
5
1.5k
3w
SwiftData ModelContext.insert crashes, why?
This simple test fails in my project. Similar code in my application also crashes. How do I debug the problem? What project settings are required. I have added SwiftData as a framework to test (and application) targets? Thanks, The problem is with: modelContext.insert(item) Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) import XCTest import SwiftData @Model class FakeModel { var name: String init(name: String) { self.name = name } } @MainActor final class FakeModelTests: XCTestCase { var modelContext: ModelContext! override func setUp() { super.setUp() do { let container = try ModelContainer(for: FakeModel.self, configurations: ModelConfiguration(isStoredInMemoryOnly: true)) modelContext = container.mainContext } catch { XCTFail("Failed to create ModelContainer: \(error)") modelContext = nil } } func testSaveFetchDeleteFakeItem() { guard let modelContext = modelContext else { XCTFail("ModelContext must be initialized") return } let item = FakeModel(name: "Test") modelContext.insert(item) let fetchDescriptor = FetchDescriptor<FakeModel>() let items = try! modelContext.fetch(fetchDescriptor) XCTAssertEqual(items.count, 1) XCTAssertEqual(items.first?.name, "Test") modelContext.delete(item) let itemsAfterDelete = try! modelContext.fetch(fetchDescriptor) XCTAssertEqual(itemsAfterDelete.count, 0) } }
4
0
181
3w
SwiftData Fatal error: Editors must register their identifiers before invoking operations on this store
I have a UIKit app where I've adopted SwiftData and I'm struggling with a crash coming in from some of my users. I'm not able to reproduce it myself and as it only happens to a small fraction of my user base, it seems like a race condition of some sort. This is the assertion message: SwiftData/DefaultStore.swift:453: Fatal error: API Contract Violation: Editors must register their identifiers before invoking operations on this store SwiftData.DefaultStore: 00CF060A-291A-4E79-BEC3-E6A6B20F345E did not. (ID is unique per crash) This is the ModelActor that crashes: @available(iOS 17, *) @ModelActor actor ConsumptionDatabaseStorage: ConsumptionSessionStorage { struct Error: LocalizedError { var errorDescription: String? } private let sortDescriptor = [SortDescriptor(\SDConsumptionSession.startTimeUtc, order: .reverse)] static func createStorage(userId: String) throws -> ConsumptionDatabaseStorage { guard let appGroupContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: UserDefaults.defaultAppGroupIdentifier) else { throw Error(errorDescription: "Invalid app group container ID") } func createModelContainer(databaseUrl: URL) throws -> ModelContainer { return try ModelContainer(for: SDConsumptionSession.self, SDPriceSegment.self, configurations: ModelConfiguration(url: databaseUrl)) } let databaseUrl = appGroupContainer.appendingPathComponent("\(userId).sqlite") do { return self.init(modelContainer: try createModelContainer(databaseUrl: databaseUrl)) } catch { // Creating the model storage failed. Remove the database file and try again. try? FileManager.default.removeItem(at: databaseUrl) return self.init(modelContainer: try createModelContainer(databaseUrl: databaseUrl)) } } func isStorageEmpty() async -> Bool { (try? self.modelContext.fetchCount(FetchDescriptor<SDConsumptionSession>())) ?? 0 == 0 // <-- Crash here! } func sessionsIn(interval: DateInterval) async throws -> [ConsumptionSession] { let fetchDescriptor = FetchDescriptor(predicate: #Predicate<SDConsumptionSession> { sdSession in if let startDate = sdSession.startTimeUtc { return interval.start <= startDate && interval.end > startDate } else { return false } }, sortBy: self.sortDescriptor) let consumptionSessions = try self.modelContext.fetch(fetchDescriptor) // <-- Crash here! return consumptionSessions.map { ConsumptionSession(swiftDataSession: $0) } } func updateSessions(sessions: [ConsumptionSession]) async throws { if #unavailable(iOS 18) { // Price segments are duplicated if re-inserted so unfortunately we have to delete and reinsert sessions. // On iOS 18, this is enforced by the #Unique macro on SDPriceSegment. let sessionIds = Set(sessions.map(\.id)) try self.modelContext.delete(model: SDConsumptionSession.self, where: #Predicate<SDConsumptionSession> { sessionIds.contains($0.id) }) } for session in sessions { self.modelContext.insert(SDConsumptionSession(consumptionSession: session)) } if self.modelContext.hasChanges { try self.modelContext.save() } } func deleteAllSessions() async { if #available(iOS 18, *) { try? self.modelContainer.erase() } else { self.modelContainer.deleteAllData() } } } The actor conforms to this protocol: protocol ConsumptionSessionStorage { func isStorageEmpty() async -> Bool func hasCreditCardSessions() async -> Bool func sessionsIn(interval: DateInterval) async throws -> [ConsumptionSession] func updateSessions(sessions: [ConsumptionSession]) async throws func deleteAllSessions() async } The crash is coming in from line 30 and 41, in other words, when trying to fetch data from the database. There doesn't seem to be any common trait for the crashes. They occur across iOS versions and device types. Any idea what might cause this?
5
0
168
3w
Why is CKModifyRecordsOperation to batch delete records in CloudKit not deleting records?
My Code: let op = CKModifyRecordsOperation(recordIDsToDelete:recordIDsToDelete) op.modifyRecordsCompletionBlock = { _, deleteRecordIDs, error in if error == nil { print("successful delete deleteRecordIDS = \(deleteRecordIDs)") } else { print("delete error = \(error?.localizedDescription)") } } op.database = CKContainer.default().privateCloudDatabase op.qualityOfService = .userInitiated CKContainer.default().privateCloudDatabase.add(op) My problem is that CKRecord are not deleted once I reinstall the app: when I reinstall the app and try to delete a CloudKit record, the method is executed successfully (error is nil) but the records are still in CloudKit Dashboards.
2
0
186
3w
SwiftData crash when switching between Window and ImmersiveSpace in visionOS
Environment visionOS 26 Xcode 26 Issue I am experiencing crash when trying to access a [String] from a @Model data, after dismissing an immersiveSpace and opening a WindowGroup. This crash only occurs when trying to access the [String] property of my Model. It works fine with other properties. Thread 1: Fatal error: This backing data was detached from a context without resolving attribute faults: PersistentIdentifier(...) Steps to Reproduce Open WindowGroup Dismiss window, open ImmersiveSpace Dismiss ImmersiveSpace, reopen WindowGroup Any guidance would be appreciated! @main struct MyApp: App { var body: some Scene { WindowGroup(id: "main") { ContentView() } .modelContainer(for: [Item.self]) ImmersiveSpace(id: "immersive") { ImmersiveView() } } } // In SwiftData model @Model class Item { var title: String = "" // Accessing this property works fine var tags: [String] = [] @storageRestrictions(accesses: _$backingData, initializes: _tags) init(initialValue) { _$backingData.setValue(forKey: \. tags, to: initialValue) _tags =_ SwiftDataNoType() } get { _$observationRegistrar.access(self, keyPath: \.tags) **return self getValue(forkey: \.tags)** // Crashes here }
3
0
119
4w
Xcode 26: Sendable checking + NSManagedObjectContext.perform in Swift 6
I have some code which handles doing some computation on a background thread before updating Core Data NSManagedObjects by using the NSManagedObjectContext.perform functions. This code is covered in Sendable warnings in Xcode 26 (beta 6) because my NSManagedObject subclasses (autogenerated) are non-Sendable and NSManagedObjectContext.perform function takes a Sendable closure. But I can't really figure out what I should be doing. I realize this pattern is non-ideal for Swift concurrency, but it's what Core Data demands AFAIK. How do I deal with this? let moc = object.managedObjectContext! try await moc.perform { object.completed = true // Capture of 'object' with non-Sendable type 'MySpecialObject' in a '@Sendable' closure try moc.save() } Thanks in advance for your help!
1
1
110
4w
CloudKit console fails to query indexed records in Production
"No records found" If I create a new record on the console, I can copy the record name. I can then query for recordName and get that individual record back. BUT no other queries work. I cannot query all records. I cannot query by individual property. Just returns "no records found" Seems like my indexes got messed up. Is there a way to reset indexes on prod? This is on a coredata.cloudkit managed zone.
1
0
73
4w
CloudKit: Records not indexing
Since publishing new record types to my CloudKit schema in production, a previously unchanged record type has stopped indexing new records. While records of this type are successfully saved without errors, they are not returned in query results—they can only be accessed directly via their recordName. This issue occurs exclusively in the Production environment, both in the CloudKit Console and our iOS app. The problem began on July 21, 2025, and continues to persist. The issue affects only new records of this specific record type; all other types are indexing and querying as expected. The affected record's fields are properly configured with the appropriate index types (e.g., QUERYABLE) and have been not been modified prior to publishing the schema. With this, are there any steps I should take to restore indexing functionality for this record type in Production? There have been new records inserted, and I would prefer to not have to reset the production database, if possible.
4
1
182
4w
SwiftData initializing Optional Array to Empty Array
I've been seeing something that I find odd when using two SwiftData models where if I have one model (book, in this case) that has an optional array of another model (page, in this case), the optional array starts out as set to nil, but after about 20 seconds it updates to being an empty array. I see it in Previews and after building. Is this expected behavior? Should I just assume that if there is an optional array in my model it will eventually be initialized to an empty array? Code is below. import SwiftUI import SwiftData @Model final class Book { var title: String = "New Book" @Relationship var pages: [Page]? = nil init(title: String) { self.title = title } } @Model final class Page { var content: String = "Page Content" var book: Book? = nil init() { } } struct ContentView: View { @Environment(\.modelContext) private var modelContext @Query private var books: [Book] var body: some View { NavigationSplitView { List { ForEach(books) { book in NavigationLink { Text("\(book.title)") Text(book.pages?.debugDescription ?? "pages is nil") } label: { Text("\(book.title)") Spacer() Text("\(book.pages?.count.description ?? "pages is nil" )") } } } HStack { Button("Clear Data") { clearData() } Button("Add Book") { addBook() } } .navigationSplitViewColumnWidth(min: 180, ideal: 200) } detail: { Text("Select an item") } } private func clearData() { for book in books { modelContext.delete(book) } try? modelContext.save() } private func addBook() { let newBook = Book(title: "A New Book") modelContext.insert(newBook) } } @main struct BookPageApp: App { var sharedModelContainer: ModelContainer = { let schema = Schema([Book.self, Page.self]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() var body: some Scene { WindowGroup { ContentView() } .modelContainer(sharedModelContainer) } } #Preview { ContentView() .modelContainer(for: Book.self, inMemory: true) }
1
0
99
4w
How to get PersistentIdentifier from a model created in a transaction?
I have a ModelActor that creates a hierarchy of models and returns a PersistentIdentifier for the root. I'd like to do that in a transaction, but I don't know of a good method of getting that identifier if the models are created in a transaction. For instance, an overly simple example: func createItem(timestamp: Date) throws -> PersistentIdentifier { try modelContext.transaction { let item = Item(timestamp: timestamp) modelContext.insert(item) } // how to return item.persistentModelID? } I can't return the item.persistentModelID from the transaction closure and even if I could, it will be a temporary ID until after the transaction is executed. I can't create the Item outside the transaction and just have the transaction do an insert because swift will raise a data race error if you then try to return item.persistentModelID. Is there any way to do this besides a modelContext.fetch* with separate unique identifiers?
2
0
161
4w
Importing Data into SwiftData in the Background Using ModelActor and @Query
I have an app with fairly typical requirements - I need to insert some data (in my case from the network but could be anything) and I want to do it in the background to keep the UI responsive. I'm using SwiftData. I've created a ModelActor that does the importing and using the debugger I can confirm that the data is indeed being inserted. On the UI side, I'm using @Query and a SwiftUI List to display the data but what I am seeing is that @Query is not updating as the data is being inserted. I have to quit and re-launch the app in order for the data to appear, almost like the context running the UI isn't communicating with the context in the ModelActor. I've included a barebones sample project. To reproduce the issue, tap the 'Background Insert' button. You'll see logs that show items being inserted but the UI is not showing any data. I've tested on the just released iOS 18b3 seed (22A5307f). The sample project is here: https://hanchor.s3.amazonaws.com/misc/SwiftDataBackgroundV2.zip
23
13
5.4k
Aug ’25
NSCocoaErrorDomain Code=513 after user delete's
I work on an app that saves data to the Documents folder in the users iCloud Drive. This uses the iCloud -> iCloud Documents capability with a standard container. We've noticed an issue where a user will delete the apps data by doing to Settings > {Name} > iCloud > Storage > App Name > select "delete data from iCloud", and then our app can no longer write to or create the Documents folder. Once that happens, we get this error: Error Domain=NSCocoaErrorDomain Code=513 "You don't have permission to save the file "Documents" in the folder "iCloud~your~bundle~identifier"." UserInfo={NSFilePath=/private/var/mobile/Library/Mobile Documents/iCloud~your~bundle~identifier/Documents, NSURL=file:///private/var/mobile/Library/Mobile%20Documents/iCloud~your~bundle~identifier/Documents, NSUnderlyingError=0x1102c7ea0 {Error Domain=NSPOSIXErrorDomain Code=13 "Permission denied"}} This is reproducible using the sample project here https://developer.apple.com/documentation/uikit/synchronizing-documents-in-the-icloud-environment. Steps to reproduce in that project: Tap the plus sign in the top right corner to create a new document Add a document name and tap "Save to Documents" Go to Settings > {Name} > iCloud > Storage > SimpleiCloudDocument App Name > select "delete data from iCloud" Reopen the app and repeat steps 1-2 Observe error on MainViewController+Document.swift:59 Deleting and reinstalling the app doesn't seem to help.
2
0
74
Aug ’25
Mixing in-memory and persistent SwiftData containers in a Document-based App?
Hello, I'm trying to work on an iPadOS and macOS app that will rely on the document-based system to create some kind of orientation task to follow. Let say task1.myfile will be a check point regulation from NYC to SF and task2.myfile will be a visit as many key location as you can in SF. The file represent the specific landmark location and rules of the game. And once open, I will be able to read KML/GPS file to evaluate their score based with the current task. But opened GPS files does not have to be stored in the task file itself, it stay alongside. I wanted to use that scenario to experiment with SwiftData (I'm a long time CoreData user, I even wrote my own WebDAV based persistent store back in the day), and so, mix both on file and in memory persistent store, with distribution based on object class. With CoreData it would have been possible, but I do not see how to achieve that with SwiftData and DocumentGroup integration. Any idea how to do that?
1
0
98
Aug ’25
SwiftData migration error: NSCloudKitMirroringDelegate are not reusable
Hello everyone, I used SwiftData for v1 of an app and am now trying to make changes to the schema for v2. I created the v2 schema that adds a property to one of the models. I need to populate the new property so I made a custom migration using didMigrate. However that doesn't seem to matter what I do in the migration because creating the ModelContainer throws an error before didMigrate ever gets called. The error is: Unresolved error loading container Error Domain=NSCocoaErrorDomain Code=134060 "A Core Data error occurred." UserInfo={NSLocalizedFailureReason=Instances of NSCloudKitMirroringDelegate are not reusable and should have a lifecycle tied to a given instance of NSPersistentStore.} Higher up in the Xcode output I see things like this (in order): Request 'D25A8CB8-7341-4FA8-B2F8-3DE2D35B5273' was cancelled because the store was removed from the coordinator. BUG IN CLIENT OF CLOUDKIT: Registering a handler for a CKScheduler activity identifier that has already been registered CloudKit setup failed because it couldn't register a handler for the export activity. There is another instance of this persistent store actively syncing with CloudKit in this process. How can I know from this output what I am doing incorrectly? Any idea what I should take a look at or try to do differently? This is a simple app with three models and nothing fancy. The only change in the schema is to add a property. The new property is declared as optional and has an inverse that is also declared as optional. Thanks for any insight!
16
7
1.2k
Aug ’25
SwiftData crash when using a @Query sort descriptor with a relationship
I am using SwiftData for storage and have a view that uses the @Query property wrapper with a sort descriptor that points to a relationship on a model. In a release build on device running iOS 18.3, the app crashes. This is the line that crashes: @Query(sort: \Item.info.endDate, order: .reverse) private var items: [Item] Item has a relationship to ItemInfo, which is where the endDate property is defined. This code works in debug and on a simulator. In the project referenced here: https://github.com/lepolt/swiftdata-crash, change the scheme build configuration to “Release” and run on device. The app will crash. Using Xcode Version 16.2 (16C5032a) iPhone 12, iOS 18.3 (22D60)
9
12
1.3k
Aug ’25
SwiftData unversioned migration
Hi, I'm struggling with SwiftData and the components for migration and could really use some guidance. My specific questions are Is it possible to go from an unversioned schema to a versioned schema? Do all @Model classes need to be converted? Is there one VersionedSchema for the entire app that handles all models or one VersionedSchema per model? What is the relationship, if any, between the models given to ModelContainer in a [Schema] and the models in the VersionedSchema in a [any PersistentModel.Type] I have an app in the AppStore. I use SwiftData and have four @Models defined. I was not aware of VersionedSchema when I started, so they are unversioned. I want to update the model and am trying to convert to a VersionedSchema. I've tried various things and can't even get into the migration plan yet. All posts and tutorials that I've come across only deal with one Model, and create a VersionedSchema for that model. I've tried to switch the one Model I want to update, as well as switching them all. Of course I get different errors depending on what configuration I try. It seems like I should have one VersionedSchema for the app since there is the static var models: [any PersistentModel.Type] property. Yet the tutorials I've seen create a TypeNameSchemaV1 to go with the @Model TypeName. Which is correct? An AppNameSchemaV1 which defines four models, or four TypeNameSchemaV1? Any help will be much appreciated
14
3
3.4k
Aug ’25