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: filtering against an array of PersistentIdentifiers
I would like to have a SwiftData predicate that filters against an array of PersistentIdentifiers. A trivial use case could filtering Posts by one or more Categories. This sounds like something that must be trivial to do. When doing the following, however: let categoryIds: [PersistentIdentifier] = categoryFilter.map { $0.id } let pred = #Predicate<Post> { if let catId = $0.category?.persistentModelID { return categoryIds.contains(catId) } else { return false } } The code compiles, but produces the following runtime exception (XCode 26 beta, iOS 26 simulator): 'NSInvalidArgumentException', reason: 'unimplemented SQL generation for predicate : (TERNARY(item != nil, item, nil) IN {}) (bad LHS)' Strangely, the same code works if the array to filter against is an array of a primitive type, e.g. String or Int. What is going wrong here and what could be a possible workaround?
3
0
91
Jun ’25
Avoid Duplicate Records with CloudKit & CoreData
When my app starts it loads data (of vehicle models, manufacturers, ...) from JSON files into CoreData.  This content is static. Some CoreData entities have fields that can be set by the user, for example an isFavorite boolean field. How do I tell CloudKit that my CoreData objects are 'static' and must not be duplicated on other devices (that will also load it from JSON files). In other words, how can I make sure that the CloudKit knows that the record created from JSON for vehicle model XYZ on one device is the same record that was created from JSON on any other device? I'm using NSPersistentCloudKitContainer.
3
2
3.2k
Jun ’25
SwiftData serious bug with relationships and CloudKit in iOS 18.0 (Xcode 16 Beta)
Hi guys. Can someone please confirm this bug so I report it? The issue is that SwiftData relationships don't update the views in some specific situations on devices running iOS 18 Beta. One clear example is with CloudKit. I created a small example for testing. The following code creates two @models, one to store bands and another to store their records. The following code works with no issues. (You need to connect to a CloudKit container and test it on two devices) import SwiftUI import SwiftData struct ContentView: View { @Environment(\.modelContext) private var modelContext @Query private var records: [Record] var body: some View { NavigationStack { List(records) { record in VStack(alignment: .leading) { Text(record.title) Text(record.band?.name ?? "Undefined") } } .toolbar { ToolbarItem { Button("Add Record") { let randomNumber = Int.random(in: 1...100) let newBand = Band(name: "New Band \(randomNumber)", records: nil) modelContext.insert(newBand) let newRecord = Record(title: "New Record \(randomNumber)", band: newBand) modelContext.insert(newRecord) } } } } } } @Model final class Record { var title: String = "" var band: Band? init(title: String, band: Band?) { self.title = title self.band = band } } @Model final class Band { var name: String = "" var records: [Record]? init(name: String, records: [Record]?) { self.name = name self.records = records } } This view includes a button at the top to add a new record associated with a new band. The data appears on both devices, but if you include more views inside the List, the views on the second device are not updated to show the values of the relationships. For example, if you extract the row to a separate view, the second device shows the relationships as "Undefined". You can try the following code. struct ContentView: View { @Environment(\.modelContext) private var modelContext @Query private var records: [Record] var body: some View { NavigationStack { List { ForEach(records) { record in RecordRow(record: record) } } .toolbar { ToolbarItem { Button("Add Record") { let randomNumber = Int.random(in: 1...100) let newBand = Band(name: "New Band \(randomNumber)", records: nil) modelContext.insert(newBand) let newRecord = Record(title: "New Record \(randomNumber)", band: newBand) modelContext.insert(newRecord) } } } } } } struct RecordRow: View { let record: Record var body: some View { VStack(alignment: .leading) { Text(record.title) Text(record.band?.name ?? "Undefined") } } } Here I use a ForEach loop and move the row to a separate view. Now on the second device the relationships are nil, so the row shows the text "Undefined" instead of the name of the band. I attached an image from my iPad. I inserted all the information on my iPhone. The first three rows were inserted with the first view. But the last two rows were inserted after I extracted the rows to a separate view. Here you can see that the relationships are nil and therefore shown as "Undefined". The views are not updated to show the real value of the relationship. This example shows the issue with CloudKit, but this also happens locally in some situations. The system doesn't detect updates in relationships and therefore doesn't refresh the views. Please, let me know if you can reproduce the issue. I'm using Mac Sequoia 15.1, and two devices with iOS 18.0.
3
0
793
Apr ’25
how can I discern which SwiftData object trigger the .NSManagedObjectContextDidSave notification ?
Presently, I am encountering an issue with SwiftData. For instance, I have a SwiftData class Ledger that encompasses an array of SingleTransaction, which is also a SwiftData class. Here is the question: when I save a Ledger, how can I discern that the .NSManagedObjectContextDidSave notification was triggered by saving the Ledger and not by saving a SingleTransaction? This distinction is crucial to circumvent unnecessary updates. I attempted the following syntax, but Xcode indicates that Cast from NSManagedObject to unrelated type Ledger always fails. List {...} .onReceive( NotificationCenter .default .publisher(for: .NSManagedObjectContextDidSave) .receive(on: DispatchQueue.main), perform: { notification in if let userInfo = notification.userInfo, let updatedObjects = userInfo[NSUpdatedObjectsKey] as? Set<NSManagedObject> { if updatedObjects.contains(where: { $0 is Ledger }) { fetchLedgers() } } } ) What can I do?
3
0
965
Oct ’24
Mac App Crashing with Illegal Instructions
I have made a Swift App for MacOS 15 under XCode 16.3, which runs fine. I also want to run it under the previous MacOS 14. Unfortunately it crashes without even starting up (it does not even reach the first log output statement on the first view) The crash reason is Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_BAD_INSTRUCTION (SIGILL) Exception Codes: 0x0000000000000001, 0x0000000000000000 Termination Reason: Namespace SIGNAL, Code 4 Illegal instruction: 4 Terminating Process: exc handler [2970] I have set the miminium deployment to MacOS 14.0 but to no effect. The XCode machine is a MacOS 15.4 on Arm M3 and the target machine is MacOS 14.7.5 on Intel (MacBook Air) I think it might be related to the compiler and linker settings.
3
0
69
Apr ’25
Debugging help
No matter what I do, I keep getting the error Thread 1: EXC_BREAKPOINT (code=1, subcode=0x2648fc364) for the line: transactions = try modelContext.fetch(descriptor) in the code below. My app opens, but freezes on the home page and I can't click anything. I am not sure how to fix initialization issues. I am creating a financial assistant app that connects plaid and opoenai api. var descriptor = FetchDescriptor&lt;ExpenseTransaction&gt;() descriptor.sortBy = [SortDescriptor(\.date, order: .reverse)] descriptor.fetchLimit = 200 transactions = try modelContext.fetch(descriptor) print("Successfully loaded \(transactions.count) transactions") } catch { print("Error in loadLocalTransactions: \(error)") transactions = [] } }
3
0
75
Apr ’25
can't reach CloudKit dashboard
Hello there, I have a problem reaching the CloudKit dashboard. Every time I login, the login successes but then I get the error: An error has caused this web page to stop working correctly. This also happens when I click on the Button CloudKit dashboard. Then I can reload the page, but the same errors occurs again and again. Can someone help me with this problem? Thank you very much
3
4
122
May ’25
Issues with SwiftData One-to-Many Relationships
I've been working with SwiftData and encountered a perplexing issue that I hope to get some insights on. When using a @Model that has a one-to-many relationship with another @Model, I noticed that if there are multiple class variables involved, SwiftData seems to struggle with correctly associating each variable with its corresponding data. For example, in my code, I have two models: Book and Page. The Book model has a property for a single contentPage and an optional array of pages. However, when I create a Book instance and leave the pages array as nil, iterating over pages unexpectedly returns the contentPage instead. You can check out the code for more details here. Has anyone else faced this issue or have any suggestions on how to resolve it? Any help would be greatly appreciated! I dont understand. How does using appended help here? I am not adding anything to the array. Here is the summary The following code defines two SwiftData models: Book and Page. In the Book class, there is a property contentPage of type Page, and an optional array pages that holds multiple Page instances. @Model class Book { var id = UUID() var title: String var contentPage: Page var pages: [Page]? init(id: UUID = UUID(), title: String, contentPage: Page) { self.id = id self.title = title self.contentPage = contentPage contentPage.book = self } func addPage(page: Page) { if pages == nil { pages = [] } page.book = self pages?.append(page) } } enum PageType: String, Codable { case contentsPage = "Contents" case picturePage = "Picture" case textPage = "Text" case blankPage = "Blank" } @Model class Page { var id = UUID() var pageType: PageType var pageNumber: Int var content: String var book: Book? init(id: UUID = UUID(), pageType: PageType, content: String, pageNumber: Int) { self.id = id self.pageType = pageType self.pageNumber = pageNumber self.content = content } } Observed Behavior: With the code above, I created a Book instance and populated all fields except for the pages, which was left as nil. However, when I attempt to iterate over the pages, I receive the contentPage instead. This indicates that there may be an issue with how SwiftData handles these associations. Expected behavior - when iterating over pages I should not see contentPage since it is a separate property
3
0
982
Oct ’24
SwiftData + CKSyncEngine
Hi, I'm building a habit tracking app for iOS and macOS. I want to use up to date technologies, so I'm using SwiftUI and SwiftData. I want to store user data locally on device and also sync data between device and iCloud server so that the user could use the app conveniently on multiple devices (iPhone, iPad, Mac). I already tried SwiftData + NSPersistentCloudKitContainer, but I need to control when to sync data, which I can't control with NSPersistentCloudKitContainer. For example, I want to upload data to server right after data is saved locally and download data from server on every app open, on pull-to-refresh etc. I also need to monitor sync progress, so I can update the UI and run code based on the progress. For example, when downloading data from server to device is in progress, show "Loading..." UI, and when downloading finishes, I want to run some app business logic code and update UI. So I'm considering switching from NSPersistentCloudKitContainer to CKSyncEngine, because it seems that with CKSyncEngine I can control when to upload and download data and also monitor the progress. My database schema (image below) has relationships - "1 to many" and "many to many" - so it's convenient to use SwiftData (and underlying CoreData). Development environment: Xcode 16.1, macOS 15.1.1 Run-time configuration: iOS 18.1.1, macOS 15.1.1 My questions: 1-Is it possible to use SwiftData for local data storage and CKSyncEngine to sync this local data storage with iCloud? 2-If yes, is there any example code to implement this? I've been studying the "CloudKit Samples: CKSyncEngine" demo app (https://github.com/apple/sample-cloudkit-sync-engine), but it uses a very primitive approach to local data storage by saving data to a JSON file on disk. It would be very helpful to have the same demo app with SwiftData implementation! 3-Also, to make sure I don't run into problems later - is it okay to fire data upload (sendChanges) and download (fetchChanges) manually with CKSyncEngine and do it often? Are there any limits how often these functions can be called to not get "blocked" by the server? 4-If it's not possible to use SwiftData for local data storage and CKSyncEngine to sync this local data storage with iCloud, then what to use for local storage instead of SwiftData to sync it with iCloud using CKSyncEngine? Maybe use SwiftData with the new DataStore protocol instead of the underlying CoreData? All information highly appreciated! Thanks, Martin
3
0
1.3k
Dec ’24
CKShare Invitation URL sharing
CKShare provides a url that allows others to be invited. It is necessary for a potential participant to have access to this url (otherwise there is no way for them to accept the invitation). An easy solution is to send this url via the Messages application, but this is an extra step for the share owner. I have noticed that Apple's Passwords app somehow sends this url to the invited user within the Passwords app - and I wonder if this is possible with just public Apple apis, or if Apple uses some private api to achieve this.
3
0
921
Oct ’24
CoreData/CloudKit 0xdead10cc
I’m getting a 0xdead10cc crash in a basic CoreData/CloudKit application. I only have one CoreData save call and its made when the app is in the foreground and it's minor so I don't think its being caused by that. My best guess is that it's related to background syncing of CloudKit. Does anyone know how to fix it? I've been advised that adding the following code around any saves will fix it, but it seems weird that this is the solution. I would expect the inner CoreData/CloudKit engine to handle this. ProcessInfo().performActivity(reason: "Persisting to context") { // Save to context here } Here is the crashing thread Thread 7: 0 libsystem_kernel.dylib 0x00000001edc086f4 guarded_pwrite_np + 8 (:-1) 1 libsqlite3.dylib 0x00000001ca71b6e4 seekAndWrite + 456 (sqlite3.c:44287) 2 libsqlite3.dylib 0x00000001ca6d5df4 unixWrite + 180 (sqlite3.c:44365) 3 libsqlite3.dylib 0x00000001ca723b90 pagerWalFrames + 872 (sqlite3.c:67093) 4 libsqlite3.dylib 0x00000001ca6d5b14 sqlite3PagerCommitPhaseOne + 316 (sqlite3.c:70409) 5 libsqlite3.dylib 0x00000001ca6c6494 sqlite3BtreeCommitPhaseOne + 172 (sqlite3.c:81106) 6 libsqlite3.dylib 0x00000001ca6c605c vdbeCommit + 1136 (sqlite3.c:94124) 7 libsqlite3.dylib 0x00000001ca69f778 sqlite3VdbeHalt + 1340 (sqlite3.c:94534) 8 libsqlite3.dylib 0x00000001ca6c0618 sqlite3VdbeExec + 42648 (sqlite3.c:103922) 9 libsqlite3.dylib 0x00000001ca6b56c0 sqlite3_step + 960 (sqlite3.c:97886) 10 CoreData 0x00000001a459ab38 _execute + 128 (NSSQLiteConnection.m:4614) 11 CoreData 0x00000001a45fe004 -[NSSQLiteConnection commitTransaction] + 728 (NSSQLiteConnection.m:3278) 12 CoreData 0x00000001a469888c _executeGenerateObjectIDRequest + 388 (NSSQLCore_Functions.m:6021) 13 CoreData 0x00000001a46986a4 -[NSSQLGenerateObjectIDRequestContext executeRequestCore:] + 28 (NSSQLObjectIDRequestContext.m:42) 14 CoreData 0x00000001a45fb380 -[NSSQLStoreRequestContext executeRequestUsingConnection:] + 240 (NSSQLStoreRequestContext.m:183) 15 CoreData 0x00000001a45fb0a8 __52-[NSSQLDefaultConnectionManager handleStoreRequest:]_block_invoke + 60 (NSSQLConnectionManager.m:307) 16 CoreData 0x00000001a45fafe0 __37-[NSSQLiteConnection performAndWait:]_block_invoke + 48 (NSSQLiteConnection.m:755) 17 libdispatch.dylib 0x00000001a4357fa8 _dispatch_client_callout + 20 (object.m:576) 18 libdispatch.dylib 0x00000001a43677fc _dispatch_lane_barrier_sync_invoke_and_complete + 56 (queue.c:1104) 19 CoreData 0x00000001a45b5ba4 -[NSSQLiteConnection performAndWait:] + 176 (NSSQLiteConnection.m:752) 20 CoreData 0x00000001a45b5a68 -[NSSQLDefaultConnectionManager handleStoreRequest:] + 248 (NSSQLConnectionManager.m:302) 21 CoreData 0x00000001a45b5938 -[NSSQLCoreDispatchManager routeStoreRequest:] + 228 (NSSQLCoreDispatchManager.m:60) 22 CoreData 0x00000001a45b573c -[NSSQLCore dispatchRequest:withRetries:] + 172 (NSSQLCore.m:4044) 23 CoreData 0x00000001a46737b4 -[NSSQLCore _obtainPermanentIDsForObjects:withNotification:error:] + 1324 (NSSQLCore.m:2830) 24 CoreData 0x00000001a460ba98 -[NSSQLCore _prepareForExecuteRequest:withContext:error:] + 272 (NSSQLCore.m:2946) 25 CoreData 0x00000001a460a0f8 __65-[NSPersistentStoreCoordinator executeRequest:withContext:error:]_block_invoke.547 + 8988 (NSPersistentStoreCoordinator.m:2995) 26 CoreData 0x00000001a45d6660 -[NSPersistentStoreCoordinator _routeHeavyweightBlock:] + 264 (NSPersistentStoreCoordinator.m:668) 27 CoreData 0x00000001a45ded28 -[NSPersistentStoreCoordinator executeRequest:withContext:error:] + 1200 (NSPersistentStoreCoordinator.m:2810) 28 CoreData 0x00000001a4655988 -[NSManagedObjectContext save:] + 984 (NSManagedObjectContext.m:1593) 29 CoreData 0x00000001a46f47dc __52+[NSCKEvent beginEventForRequest:withMonitor:error:]_block_invoke_2 + 352 (NSCKEvent.m:76) 30 CoreData 0x00000001a45c28f0 developerSubmittedBlockToNSManagedObjectContextPerform + 476 (NSManagedObjectContext.m:3984) 31 libdispatch.dylib 0x00000001a4357fa8 _dispatch_client_callout + 20 (object.m:576) 32 libdispatch.dylib 0x00000001a43677fc _dispatch_lane_barrier_sync_invoke_and_complete + 56 (queue.c:1104) 33 CoreData 0x00000001a4615c34 -[NSManagedObjectContext performBlockAndWait:] + 308 (NSManagedObjectContext.m:4108) 34 CoreData 0x00000001a46f45ac __52+[NSCKEvent beginEventForRequest:withMonitor:error:]_block_invoke + 192 (NSCKEvent.m:66) 35 CoreData 0x00000001a4825e68 -[PFCloudKitStoreMonitor performBlock:] + 92 (PFCloudKitStoreMonitor.m:148) 36 CoreData 0x00000001a46f4394 +[NSCKEvent beginEventForRequest:withMonitor:error:] + 256 (NSCKEvent.m:61) 37 CoreData 0x00000001a47cc6ec __57-[NSCloudKitMirroringDelegate _performExportWithRequest:]_block_invoke + 260 (NSCloudKitMirroringDelegate.m:1433) 38 CoreData 0x00000001a47c9970 __92-[NSCloudKitMirroringDelegate _openTransactionWithLabel:assertionLabel:andExecuteWorkBlock:]_block_invoke + 72 (NSCloudKitMirroringDelegate.m:957) 39 libdispatch.dylib 0x00000001a4356248 _dispatch_call_block_and_release + 32 (init.c:1549) 40 libdispatch.dylib 0x00000001a4357fa8 _dispatch_client_callout + 20 (object.m:576) 41 libdispatch.dylib 0x00000001a435f5cc _dispatch_lane_serial_drain + 768 (queue.c:3934) 42 libdispatch.dylib 0x00000001a4360158 _dispatch_lane_invoke + 432 (queue.c:4025) 43 libdispatch.dylib 0x00000001a436b38c _dispatch_root_queue_drain_deferred_wlh + 288 (queue.c:7193) 44 libdispatch.dylib 0x00000001a436abd8 _dispatch_workloop_worker_thread + 540 (queue.c:6787) 45 libsystem_pthread.dylib 0x0000000227213680 _pthread_wqthread + 288 (pthread.c:2696) 46 libsystem_pthread.dylib 0x0000000227211474 start_wqthread + 8 (:-1)
3
0
761
Jan ’25
SwiftData SchemaMigrationPlan and VersionedSchema not Sendable?
I've just tried to update a project that uses SwiftData to Swift 6 using Xcode 16 beta 1, and it's not working due to missing Sendable conformance on a couple of types (MigrationStage and Schema.Version): struct LocationsMigrationPlan: SchemaMigrationPlan { static let schemas: [VersionedSchema.Type] = [LocationsVersionedSchema.self] static let stages: [MigrationStage] = [] } struct LocationsVersionedSchema: VersionedSchema { static let models: [any PersistentModel.Type] = [ Location.self ] static let versionIdentifier = Schema.Version(1, 0, 0) } This code results in the following errors: error: static property 'stages' is not concurrency-safe because non-'Sendable' type '[MigrationStage]' may have shared mutable state static let stages: [MigrationStage] = [] ^ error: static property 'versionIdentifier' is not concurrency-safe because non-'Sendable' type 'Schema.Version' may have shared mutable state static let versionIdentifier = Schema.Version(1, 0, 0) ^ Am I missing something, or is this a bug in the current seed? I've filed this as FB13862584.
3
4
1.8k
Nov ’24
Migrating schemas in SwiftData + CloudKit
Hello, I’m struggling to go from unversioned data model in SwiftData, to starting to version it. Some FYI: I’m using CloudKit I’m using a widget, where I also pass in my data model and setup my container, this is shared over a group container/app group. My migration is very simple, I’m adding a property which is not optional ( has default value set, and a default value in initialiser ). Model: @Model class NicotineModel { var nicotineType: NicotineType = NicotineType.snus var startDate: Date = Date() + 30 var spendingAmount: Int = 0 var nicotinePerDay: Int = 0 var quittingMethod: QuittingMethod = QuittingMethod.coldTurkey // this is the change in the model, V1 doesn't have the quittingMethod property var setupComplete: Bool = false I’ve tried with: static let migrateV1toV2 = MigrationStage.lightweight( fromVersion: SchemaV1.self, toVersion: SchemaV2.self ) But also static let migrateV1toV2 = MigrationStage.custom( fromVersion: SchemaV1.self, toVersion: SchemaV2.self, willMigrate: nil, didMigrate: { context in let nicotineModels2 = try context.fetch(FetchDescriptor<SchemaV2.NicotineModel>()) let nicotineModels = try context.fetch(FetchDescriptor<SchemaV1.NicotineModel>()) for model in nicotineModels { let newModel = SchemaV2.NicotineModel( nicotineType: model.nicotineType, startDate: model.startDate, spendingAmount: model.spendingAmount, nicotinePerDay: model.nicotinePerDay, setupComplete: model.setupComplete, quittingMethod: .coldTurkey ) context.insert(newModel) context.delete(model) } try context.save() } ) and simply static let migrateV1toV2 = MigrationStage.custom( fromVersion: SchemaV1.self, toVersion: SchemaV2.self, willMigrate: nil, didMigrate: { context in let nicotineModels = try context.fetch(FetchDescriptor<SchemaV2.NicotineModel>()) for model in nicotineModels { model.quittingMethod = .coldTurkey } try context.save() } ) This gives me the error on startup SwiftData/ModelCoders.swift:1762: Fatal error: Passed nil for a non-optional keypath \NicotineModel.quittingMethod On https://icloud.developer.apple.com I can see that the record doesn't include my quittingMethod. I'm loosing my mind, what am I doing wrong?
3
3
841
Sep ’24
iOS 18 SwiftData Bug: Codable Models Cause Relationship Mapping Error
Here we have yet another bug, I suppose, in SwiftData that happens on iOS18 but it is not an issue on iOS17. There are 2 models defined as follows @Model final public class Note: Identifiable, Codable, Hashable { public private(set) var uuid = UUID().uuidString var heading: String = "" var tags: [Tag]? init(heading: String = "") { self.heading = heading } required public init(from decoder: Decoder) throws { ... } public func encode(to encoder: Encoder) throws { ... } } @Model final public class Tag: Identifiable, Codable { var name: String = "" @Relationship(deleteRule: .nullify, inverse: \Note.tags) var notes: [Note]? init(_ name: String) { self.name = name } required public init(from decoder: Decoder) throws { … } public func encode(to encoder: Encoder) throws { ... } } and a function o add new tags as follows private func addTags(note: Note, tagNames: [String]) { if note.tags == nil { note.tags = [] } for tagName in tagNames { if let tag = fetchTag(tagName) { if !note.tags!.contains(where: {$0.name == tagName}) { note.tags!.append(tag) } } else { // The following line throws the exception on iOS18 when Tag conforms to Codable: // Illegal attempt to map a relationship containing temporary objects to its identifiers. note.tags!.append(Tag(tagName)) } } } This code works perfectly well on iOS17 but on iOS18 I get the exception “Illegal attempt to map a relationship containing temporary objects to its identifiers.” What I noticed that this happens only when Tag model conforms to Codable protocol. Is it a bug? It looks like, otherwise we've got some undocumented changes have been made. In my previous post I mentioned about the other issue about ModelContext that is broken too on iOS18 - I mean it works perfectly well on iOS17. Demo app with an example how to workaround this problem is available here on GitHub. Repro steps: Add a note with some tags (separated by space) Edit this note and add a new tag (tag that does not exists in database) and tap Save. You should noticed that the tag hasn't been added. It works occasionally but hardly to be seen.
3
5
1.1k
Oct ’24
Core Data CloudKit stops syncing after incomprehensible archive error
Ive been getting this error on an app in the dev environment since iOS16. it continues to happen in the latest iOS release (iOS18). After this error/warning, CoreData_CloudKit stops syncing and the only way to fix it is to delete the app from all devices, reset the CloudKit dev environment, reload the schema and reload all data. im afriad that if I ever go live and get this error in production there won't be a way to fix it given I cant go and reset the production CloudKit environment. It doesn't happen straight away after launching my app in a predictable manner, it can take several weeks to happen. Ive posted about this before here and haven't got a response. I also have a feedback assistant issue submitted in 2022 as part of ios16 beta that is still open: FB10392936 for a similar issue that caused the same error. would like to submit a code level support query but it doest seem to have anything to do with my code - but rather the Apple core data CloudKit syncing mechanism. anyone have any similar issues or a way forward? > error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2200): <NSCloudKitMirroringDelegate: 0x301e884b0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringImportRequest: 0x3006f5a90> D823EEE6-EFAE-4AF7-AFED-4C9BA708703B' due to error: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x73, 0x61, 0x6d)" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x73, 0x61, 0x6d)}
3
0
1.1k
Nov ’24
UIImage causes memory to run out
I have a project that currently has data saved locally and I'm trying to get it to sync over multiple devices. Currently basic data is syncing perfectly fine, but I'm having issues getting the images to convert to data. From what I've researched it because I'm using a UIImage to convert and this caches the image It works fine when there's only a few images, but if there's several its a pain The associated code func updateLocalImages() { autoreleasepool { let fetchRequest: NSFetchRequest&lt;Project&gt; = Project.fetchRequest() fetchRequest.predicate = NSPredicate(format: "converted = %d", false) fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Project.statusOrder?.sortOrder, ascending: true), NSSortDescriptor(keyPath: \Project.name, ascending: true)] do { let projects = try viewContext.fetch(fetchRequest) for project in projects { currentPicNumber = 0 currentProjectName = project.name ?? "Error loading project" if let pictures = project.pictures { projectPicNumber = pictures.count for pic in pictures { currentPicNumber = currentPicNumber + 1 let picture : Picture = pic as! Picture if let imgData = convertImage(picture: picture) { picture.pictureData = imgData } } project.converted = true saveContext() } } } catch { print("Fetch Failed") } } } func convertImage(picture : Picture)-&gt; Data? { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let path = paths[0] if let picName = picture.pictureName { let imagePath = path.appendingPathComponent(picName) if let uiImage = UIImage(contentsOfFile: imagePath.path) { if let imageData = uiImage.jpegData(compressionQuality: 0.5) { return imageData } } } return nil }```
3
0
982
Jan ’25
How to provide visual feedback about iCloud sync status when the user reinstalls an app?
It takes a few seconds, sometimes a few minutes for records to be downloaded back from CloudKit when the user reinstalls the app, which leads users to thinking their data was lost. I would like to know if there’s any way to provide a visual feedback about the current CloudKit sync status so I can let users know their data is being in fact downloaded back to their devices.
2
0
199
Mar ’25
Debugging/Fixing deleted relationship objects with SwiftData
Using SwiftData and this is the simplest example I could boil down: @Model final class Item { var timestamp: Date var tag: Tag? init(timestamp: Date) { self.timestamp = timestamp } } @Model final class Tag { var timestamp: Date init(timestamp: Date) { self.timestamp = timestamp } } Notice Tag has no reference to Item. So if I create a bunch of items and set their Tag. Later on I add the ability to delete a Tag. Since I haven't added inverse relationship Item now references a tag that no longer exists so so I get these types of errors: SwiftData/BackingData.swift:875: Fatal error: This model instance was invalidated because its backing data could no longer be found the store. PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://EEC1D410-F87E-4F1F-B82D-8F2153A0B23C/Tag/p1), implementation: SwiftData.PersistentIdentifierImplementation) I think I understand now that I just need to add the item reference to Tag and SwiftData will nullify all Item references to that tag when a Tag is deleted. But, the damage is already done. How can I iterate through all Items that referenced a deleted tag and set them to nil or to a placeholder Tag? Or how can I catch that error and fix it when it comes up? The crash doesn't occur when loading an Item, only when accessing item.tag?.timestamp, in fact, item.tag?.id is still ok and doesn't crash since it doesn't have to load the backing data. I've tried things like just looping through all items and setting tag to nil, but saving the model context fails because somewhere in there it still tries to validate the old value. Thanks!
2
0
322
Mar ’25
Does CloudKit guarantee CKRecord.Reference is always valid?
I'm considering using CloudKit in my app (it doesn't use Core Data) and have read as many materials as I can find. I haven't fully grasped it yet and have a basic question on CKRecord.Reference. Does CloudKit guarantee CKRecord.Reference value is always valid? By valid I mean the target CkRecord pointed by the CKRecord.Reference exists in the database. Let's consider an example. Suppose there are two tables: Account and Transaction: Account Table: AccountNumber Currency Rate ------------- -------- ---- a1 USD 0.03 Transaction Table: TransactionNumber AccountNumber Amount ----------------- ------------- ------ t1 a1 20 Now suppose user does the following: User first deletes account a1 and its associated transactions t1 on device A. The device saves the change to cloud. Then user adds a new transaction t2 to account a1 on device B, before the device receives the change made in step 1 from cloud. Since a1 hasn't been deleted on device B, the operation should succeed locally. The device tries to save the change to cloud too. My questions: Q1) Will device B be able to save the change in step 2 to cloud? I hope it would fail, because otherwise it would lead to inconsistent data. But I find the following in CKModifyRecordsOperation doc (emphasis mine), which implies CloudKit allows invalid reference: During a save operation, CloudKit requires that the target record of the parent reference, if set, exists in the database or is part of the same operation; all other reference fields are exempt from this requirement. (BTW, I think the fact that, when using CloudKit, Core Data requires all relations must be optional also indicates that CloudKit can't guarantee relation is always valid, though I think that is mainly an issue on client side caused by data transfer size. The above example, however, is different in that it's an issue on cloud side - the data on cloud is inconsistent). I also find the following in the document. However, I don't think it helps in the above example, because IIUC CloudKit can only detect conflict when the changes on the same record but the changes in step 1 and step 2 are on different records. Because records can change between the time you fetch them and the time you save them, the save policy determines whether new changes overwrite existing changes. By default, the operation reports an error when there’s a newer version on the server. If the above understanding is correct, however, I don't understand why the same document has the following requirement, which implies CloudKit doesn't allow invalid reference: When creating two new records that have a reference between them, use the same operation to save both records at the same time. Q2) Suppose CloudKit allows invalid reference on cloud side (that is, device B successfully saves the change in step 2 to cloud) , I wonder what's the best practice to deal with it? I think the issue is different from the optional relation requirement in Core Data when using CloudKit, because in that case the data is consistent on cloud side and eventually the client will receive complete data. In the above example, however, the data on cloud is inconsistent so the client has to remedy it somehow (although client has little information helping it). One approach I think of is to avoid the issue in the first place. My idea is to maintain a counter in the database and requires client to increase the counter (it's not Lamport clock. BTW, is it possible to use Lamport clock in this case?) when making any change. This should help CloudKit to detect conflict (though I can't think out a good strategy on how client should deal with it. A simple one is perhaps to prompt user to select one copy). However, this approach effectively uses cloud as a centralized server, which I suspect isn't the typical way how people use CloudKit, and it requires clients to maintain local counter value in various situations. I wonder what's the typical approach? Am I missing something? Thanks for any help.
2
0
909
Oct ’24