iCloud & Data

RSS for tag

Learn how to integrate your app with iCloud and data frameworks for effective data storage

CloudKit Documentation

Post

Replies

Boosts

Views

Activity

Getting a crash for SwiftData that only happens on iPhone 16 pro
I'm getting a crash in SwiftData but only on one specific device (iPhone 16 pro running 18.2 22C5131e) and not on an ipad or simulator I cant troubleshoot this crash and its quite frustrating, all I am getting is @Query(sort: \Todo.timestamp, order: .reverse) private var todos: [Todo] ForEach(todos.filter { !$0.completed }) { item in // <---crash TodoListView() } and the error is Thread 1: signal SIGABRT An abort signal terminated the process. Such crashes often happen because of an uncaught exception or unrecoverable error or calling the abort() function. and _SwiftData_SwiftUI.Query.wrappedValue.getter : τ_0_1 -> 0x105b98b58 <+160>: ldur x8, [x29, #-0x40] 0x105b98b5c <+164>: ldur x0, [x29, #-0x38] 0x105b98b60 <+168>: ldur x1, [x29, #-0x30] 0x105b98b64 <+172>: ldur x9, [x29, #-0x20] 0x105b98b68 <+176>: stur x9, [x29, #-0x28] 0x105b98b6c <+180>: ldr x8, [x8, #0x8] 0x105b98b70 <+184>: blr x8 0x105b98b74 <+188>: ldur x0, [x29, #-0x28] 0x105b98b78 <+192>: sub sp, x29, #0x10 0x105b98b7c <+196>: ldp x29, x30, [sp, #0x10] 0x105b98b80 <+200>: ldp x20, x19, [sp], #0x20 0x105b98b84 <+204>: ret How do I fix this?
0
0
139
1w
Display name for CloudKit container in the "Manage Storage" view of Settings
How can I set the display name of the CloudKit container in Settings -> iCloud -> Manage Storage. I have multiple containers, some legacy, and some for certain modules that are shared among a suite of apps. The problem is all Containers show the same name so it is not possible to advise a user which containers are safe to delete. I am using NSPersistentCloudKitContainer.
0
0
75
1w
CKSyncEngine and desiredKeys
I have a CKRecord that references an CKAsset. If I understand it correctly, CKSyncEngine would download the asset every time the record has changed on the server. (Of course it would try to use the local asset cache, but worst-case it might be already flushed) The documentation for CKAsset says that asset downloads can be prevented by limiting the requested record keys using the desiredKeys property on the fetch operation. But I don't see any possibility to set this property when using CKSyncEngine. Did I miss something? Are there any alternatives?
2
0
67
1w
Questions about CloudKit cross-device synchronization
The same macOS app is logged into the same iCloud account on two Macs. The apps on both devices can sync data with iCloud, but the data between them is isolated. When I was developing, I just enabled the CloudKit(SwiftData host in iCloud) capability and did not do anything special. I thought that the same app and the same iCloud account should sync the same data between different devices. Why is the cloud data on these two Macs isolated?
1
0
117
1w
NSPersistentCloudKitContainer not saving 50% of the time
I'm using NSPersistentCloudKitContainer to save, edit, and delete items, but it only works half of the time. When I delete an item and terminate the app and repoen, sometimes the item is still there and sometimes it isn't. The operations are simple enough: moc.delete(thing) try? moc.save() Here is my DataController. I'm happy to provide more info as needed class DataController: ObservableObject { let container: NSPersistentCloudKitContainer @Published var moc: NSManagedObjectContext init() { container = NSPersistentCloudKitContainer(name: "AppName") container.loadPersistentStores { description, error in if let error = error { print("Core Data failed to load: \(error.localizedDescription)") } } #if DEBUG do { try container.initializeCloudKitSchema(options: []) } catch { print("Error initializing CloudKit schema: \(error.localizedDescription)") } #endif moc = container.viewContext } }
1
0
104
1w
Strange behavior with 100k+ records in NSPersistentCloudKitContainer
I have been using the basic NSPersistentContainer with 100k+ records for a while now with no issues. The database size can fluctuate a bit but on average it takes up about 22mb on device. When I switch the container to NSPersistentCloudKitContainer, I see a massive increase in size to ~150mb initially. As the sync engine uploads records to iCloud it has ballooned to over 600mb on device. On top of that, the user's iCloud usage in settings reports that it takes up 1.7gb in the cloud. I understand new tables are added and history tracking is enabled but the size increase seems a bit drastic. I'm not sure how we got from 22mb to 1.7gb with the exact same data. A few other things that are important to note: I import all the 100k+ records at once when testing the different containers. At the time of the initial import there is only 1 relation (an import group record) that all the records are attached to. I save the background context only once after all the records and the import group have been made and added to the context. After the initial import, some of these records may have a few new relations added to them over time. I suppose this could be causing some of the size increase, but its only about 20,000 records that are updated. None of the records include files/ large binary data. Most of the attributes are encrypted. I'm syncing to the dev iCloud environment. When I do make a change to a single attribute in a record, CloudKit reports that every attribute has been modified (not sure if this is normal or not ) Also, When syncing to a new device, the sync can take hours - days. I'm guessing it's having to sync both the new records and the changes, but it exponentially gets slower as more records are downloaded. The console will show syncing activity, but new records are being added at a slower rate as more records are added. After about 50k records, it grinds to a halt and while the console still shows sync activity, only about 100 records are added every hour. All this to say i'm very confused where these issues are coming from. I'm sure its a combination of how i've setup my code and the vast record count, record history, etc. If anyone has any ideas it would be much appreciated.
2
0
337
Sep ’24
How to change from non-versioned to versioned schema in swiftdata?
My app is using SwiftData, but I deployed it to the app store with no VersionedSchema applied without thinking about migrating the model. Now I need to migrate the data and I need help from someone who has experience moving from non-versioned to versioned. Assuming I currently have a version1, version2 schema, it works fine for the initial install situation, but when I migrate to version1, version2 in an app that is listed on the app store, I run into problems. I don't have any logs to show for it. Thread 1: EXC_BAD_ACCESS (code=2, address=0x16a6578f0) If anyone has had the same experience as above, please respond, thanks! Let me know what kind of logs you need and I'll add them as a comment.
2
1
678
Dec ’23
Can't get iCloud root directory on iCould Documents
I couldn't get iCloud root directory ("iCloud Drive not available or user domain not found."). Anybody had similar issue? I don't want to CloudKit. Xcode: Version 16.0 I have done below: Settings > iCloud Backup ON Settings > iCloud > iCloud Drive ON Settings > iCloud > MyApp ON import Foundation import UIKit class BackupManager { var isiCloudEnabled: Bool { (FileManager.default.ubiquityIdentityToken != nil) } // Get the iCloud Drive folder and create a folder if needed func createFolder() -> URL? { let fileManager = FileManager.default // Access the iCloud Drive root directory (user-visible folder) guard let iCloudRootURL = fileManager.url(forUbiquityContainerIdentifier: nil)? .appendingPathComponent("Documents") else { print("iCloud Drive not available or user domain not found.") return nil } // Check if the folder exists in iCloud Drive root, if not, create it if !fileManager.fileExists(atPath: iCloudRootURL.path) { do { try fileManager.createDirectory(at: iCloudRootURL, withIntermediateDirectories: true, attributes: nil) print("Folder created in iCloud Drive") } catch { print("Error creating folder: \(error.localizedDescription)") return nil } } // Return the URL of the folder in iCloud Drive return iCloudRootURL } }
1
0
62
1w
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
13
2
1.2k
Aug ’24
error: CoreData+CloudKit: Never successfully initialized and cannot execute request - incomprehensible archive
anyone getting the following error with CloudKit+CoreData on iOS16 RC? delete/resintall app, delete user CloudKit data and reset of environment don't fix. [error] error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2044): <NSCloudKitMirroringDelegate: 0x2816f89a0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringImportRequest: 0x283abfa00> 41E6B8D6-08C7-4C73-A718-71291DFA67E4' due to error: Error Domain=NSCocoaErrorDomain Code=4864 "*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)" UserInfo={NSDebugDescription=*** -[NSKeyedUnarchiver _initForReadingFromData:error:throwLegacyExceptions:]: incomprehensible archive (0x53, 0x6f, 0x6d, 0x65, 0x20, 0x65, 0x78, 0x61)}
5
0
1.5k
Sep ’22
SwiftData: Failed to decode a composite attribute
I changed an enum value from this: enum Kind: String, Codable, CaseIterable { case credit } to this: enum Kind: String, Codable, CaseIterable { case credit = "Credit" } And now it fails to load the data. This is inside of a SwiftData model. I get why the error is occurring, but is there a way to resolve this issue without having to revert back or delete the data? Error: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "Cannot initialize Kind from invalid String value credit", underlyingError: nil))
3
0
214
1w
SwiftData migration plan in app and widget
I have an app and widget that share access to a SwiftData container using App Groups. I have implemented a SwiftData migration plan, but I am unsure whether I should allow the widget to perform the migration (in addition to the app). I am concerned about two possible issues: If the app and widget are run at approximately the same time (e.g. the user taps Open after doing a manual update in the App Store), then both the app and widget might try to perform the migration at the same time, which could lead to race conditions / data corruption. If the widget is first to run but the widget gets suspended for some reasons (e.g., iOS decides it's using too many resources), then the migration might be suspended leaving the database in an corrupted state. To me, it feels like the safest option is to only allow the app itself to perform the migration – this will ensure that the migration can only happen once in a safe state. However, this will lead to problems for the widget. For example, if the user does not open the app for several days after an automatic update, the widget will be in a broken state, since it will not be able to open the container until it has been migrated by the app. Possible solutions I'm considering: Allow both the app and widget to perform the migration and cross my fingers. (Ignore Issue 1 and Issue 2) Implement some kind of UserDefaults flag that is set to true during migration, so that the app and widget will avoid performing the migration concurrently. (Solves Issue 1 but not Issue 2) Only perform the migration in the app, and then add code to the widget to detect which container version the widget has access to, so that the widget can continue to work with a v1 container until the app eventually updates it to a v2 container. (Solves Issue 1 and Issue 2, but leads to very convoluted code – especially over time) Things I'm unsure about: Will iOS continue to use v1 of the widget until the app is opened for the first time, at which point v2 of the widget is installed? Or does iOS immediately update the widget to v2 on update? Does iOS immediately refresh the widget timeline on update? Does SwiftData already have some logic to avoid migrations being performed twice, even from different threads? If so, how does it respond if one process tries to access a container while another process is performing a migration? Does anyone have any recommendations about how to handle these possible issues? What are best practices? Cheers!
0
1
106
1w
UndoManager with SwiftData Not Registering Single Undo Actions Properly in macOS Sonoma 14.x
I am encountering an issue with the UndoManager functionality in a SwiftUI application that integrates SwiftData for persistence. This issue occurs specifically in macOS 14 (Sonoma) but works as expected on macOS 15 (Sequoia). The focused test app I have prepared for demonstration allows users to create ParentItem objects, and for each ParentItem, users can add multiple ChildItem objects. The undo functionality (via Cmd+Z) is not working as expected in Sonoma. When I try to undo a ChildItem addition, the UndoManager does not revert just the last ChildItem added, but instead removes all ChildItems that were added in that session. Expected Behavior On macOS 14 (Sonoma), I expect the UndoManager to undo only the most recent transaction (in this case, a single ChildItem insert), similar to how it functions on macOS 15 (Sequoia). Each ChildItem insertion should be treated as a separate undoable action. Current Behavior In macOS Sonoma, pressing Cmd+Z undoes the entire list of ChildItems added to a ParentItem in the current session, rather than just the most recent ChildItem. This appears to be an issue with undo grouping, but I’ve confirmed that no explicit grouping is being used. Question Is this an issue with UndoManager in macOS Sonoma, particularly in how it interacts with SwiftData persistence? What changes should I make to ensure that each ChildItem insert is treated as an individual undo action in macOS Sonoma, just as it works in Sequoia? Any guidance on isolating the issue or recommended workarounds would be appreciated. I would expect that undo actions for each child addition would be treated as separate transactions, not grouped. Steps Taken to Solve the Problem I attempted to manually save the model context (modelContext.save()) after each ChildItem insert to ensure proper persistence. I also verified that UndoManager was not grouping operations explicitly by calling beginUndoGrouping() or endUndoGrouping() myself. This issue seems to be tied specifically to macOS Sonoma, as it does not occur on macOS Sequoia, where undoing behaves as expected. Conditions macOS 14 Sonoma: The issue occurs consistently. macOS 15 Sequoia: The issue does not occur. This issue appears to be independent of hardware, as I’ve tested it on multiple machines. APIs/Features Potentially Involved UndoManager in a SwiftUI application SwiftData for persistence (using modelContext.save()) macOS version-specific behavior Steps to reproduce Clone test project (https://github.com/Maschina/SwiftDataUndoManagerExample), compile and run Create a new ParentItem in the app (via plus toolbar button in the sidebar). Add multiple ChildItems to the ParentItem (via plus toolbar button in the content / middle column of the navigation split view). Press Cmd+Z to undo the last addition.
2
0
339
Sep ’24
CoreData iCloud Can't Sync
Only development environment can real sync. But product environment can't sync. And when run my device show this error: CoreData: Already have a mirrored relationship registered for this key: CD_M2M_Event_items:B269B612-37A6-4ED7-9FDB-601E88BF56A8:8DC64E4A-E893-4465-8B21-48CF1C52A4BC <NSCKMirroredRelationship: 0x302bb9950> (entity: NSCKMirroredRelationship; id: 0xa049af3fb0190928 <x-coredata://BEB6E57C-891C-4E71-B92F-7BAA0844913E/NSCKMirroredRelationship/p1747>; data: { cdEntityName = Event; ckRecordID = "B5908A8A-079E-482C-9F2E-1309BF071F0E"; ckRecordSystemFields = nil; isPending = 0; isUploaded = 0; needsDelete = 0; recordName = "B269B612-37A6-4ED7-9FDB-601E88BF56A8"; recordZone = "0xa049af3f6a5909a8 <x-coredata://BEB6E57C-891C-4E71-B92F-7BAA0844913E/NSCKRecordZoneMetadata/p1>"; relatedEntityName = Item; relatedRecordName = "8DC64E4A-E893-4465-8B21-48CF1C52A4BC"; relationshipName = items; }) <decode: bad range for [%@] got [offs:941 len:665 within:0]> And my product core data sync data only to October 24, 2024. The data before October 24 was synchronized normally, Nothing after October 24 is synced.
0
0
103
1w
Fulfilling a fault in Core Data throws an exception when app is in background
Hi, I have been looking into Core Data crashes happening when the app is in background and fault is fired due to some processing happening within the app. The stack looks like this where the line 5 just accesses a property of the NSManagedObject's subclass. Unfortunately I don't see any additional information about the exception itself. Therefore, I was wondering if anyone could shed some light on which exception the NSFaultHandler.m:395 is triggering and why. Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Triggered by Thread: 10 Last Exception Backtrace: 0 CoreFoundation 0x1d15b8e38 __exceptionPreprocess + 164 (NSException.m:202) 1 libobjc.A.dylib 0x1ca7478d8 objc_exception_throw + 60 (objc-exception.mm:356) 2 CoreData 0x1d8dda27c _PFFaultHandlerLookupRow + 2508 (NSFaultHandler.m:395) 3 CoreData 0x1d8e024e0 _PF_FulfillDeferredFault + 200 (NSFaultHandler.m:915) 4 CoreData 0x1d8eb8f1c _sharedIMPL_pvfk_core + 168 (NSManagedObject_Accessors.m:1198) 5 MyApp 0x103641928 closure #8 in static ChatChannel.create(fromDTO:depth:) + 304 (ChannelDTO.swift:531) At first I was thinking if this could be a case of accessing a deleted object while the context is still referencing it, but does not look like it. At least I can't reproduce it (tried deleting objects using a separate context and even with container but no crash happens). Happy to learn about different cases what could trigger exception with this stack. Notes: Contexts I use are all created with newBackgroundContext method.
0
0
87
1w
SwiftData - Context missing for optional
I have encountered an issue that when using a ModelActor to sync data in the background, the app will crash if one of the operations is to remove a PersistentModel from the context. This is running on the latest beta of Xcode 16 with visionOS 1.2 as target and in Swift 6 language mode. The code is being executed in a ModelActor. The error is first thrown by: #5 0x00000001c3223280 in PersistentModel.getValue<τ_0_0>(forKey:) () Thread 1: Fatal error: Context is missing for Optional(SwiftData.PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://97AA86BC-475D-4509-9004-D1182ABA1922/Reminder/p303), implementation: SwiftData.PersistentIdentifierImplementation)) func globalSync() async { await fetchAndSyncFolders() let result = await fetchReminders() switch result { case .success(let ekReminders): var localReminders = (try? await fetch(FetchDescriptor<Reminder>())) ?? [] // Handle local reminders with nil ekReminderID by creating new EKReminders for them for reminder in localReminders { if reminder.ekReminderID == nil { await self.createEkReminder(reminder: reminder) } } // Re-fetch local reminders to include newly created EKReminderIDs localReminders = (try? await fetch(FetchDescriptor<Reminder>())) ?? [] var localReminderDict = [String: Reminder]() for reminder in localReminders { if let ekReminderID = reminder.ekReminderID { if let existingReminder = localReminderDict[ekReminderID] { self.delete(model: existingReminder) } else { localReminderDict[ekReminderID] = reminder } } } let ekReminderDict = createReminderLookup(byID: ekReminders) await self.syncReminders(localReminders: Array(localReminderDict.values), localReminderDict: localReminderDict, ekReminderDict: ekReminderDict) // Merge duplicates await self.mergeDuplicates(localReminders: localReminders) save() case .failure(let error): print("Failed to fetch reminders: \(error.localizedDescription)") } }
27
17
3.2k
Jun ’24
[SwiftData] How to use @Query to get the first 7 elements in the list
Maybe I didn't find the relevant instructions. In my code, I only want to get the first 7 elements. At present, my code is as follows: @Query(sort:\Record.date, order: .reverse) private var records:[Record] But I wonder if once the number of records is large, will it affect the efficiency? In View, it is enough for me to count the first 7 elements in records. What should I do?
1
0
188
2w