Core Data

RSS for tag

Save your application’s permanent data for offline use, cache temporary data, and add undo functionality to your app on a single device using Core Data.

Posts under Core Data tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Access Core Data ModelContainer with SwiftData
I have an app that uses CoreData and I want to migrate to SwiftData. After following the Migrate to SwiftData session, I only need to point to my old Core Data file to read the old data and convert it to the new SwiftData format. My question is how do I do this? Maybe worth mentioning is that my NSPersistentContainer(name: "Model") is different to my app name. Possible Solution? According to a Tweet by Donny Wals this is done this way: By default a SwiftData ModelContainer will create its underlying storage in a file called default.store. If you want to change this so you can use an existing Core Data SQLite file, you can point your container to that file instead: // point to your old sqlite file let url = URL.applicationSupportDirectory.appending(path: "Model.sqlite") let config = ModelConfiguration(url: url) modelContainer = try ModelContainer(for: [ Movie.self ], config) My Tested Code @main struct SwiftData_TestApp: App { let url = URL.applicationSupportDirectory.appending(path: "Model.sqlite") let config = ModelConfiguration(url: url) let modelContainer = try ModelContainer(for: [ Item.self ], config) var body: some Scene { WindowGroup { ContentView() } .modelContainer(modelContainer) } } The problem here is that I don’t get it to work in the main app struct. When using this the way described in Dive deeper into SwiftData (at 6:58) I only get the error: Cannot use instance member 'url' within property initializer; property initializers run before 'self' is available PS: There seems to be an issue with this WWDC session method anyway – see this post.
2
0
1.7k
1d
Do remote notifications work on macOS when app is closed?
I have a native SwiftUI Mac app which is based off my iOS app and includes Core Data with iCloud sync. As per my understanding, when a user makes a change on one of the devices a remote notification is sent to the others. I have a widget which displays information from Core Data and the remote notification makes the widget update its information on the next timeline refresh without the user having to open the app manually. My question is, if an app is closed on macOS so it's not even running in the Dock, do remote notifications work? This page says "the delegate receives this message when the application is running and a remote notification arrives for it". Does that mean the app won't receive remote CloudKit notifications when closed on macOS?
1
0
70
1d
CloudKit NSPersistentCloudKitContainer Bug
Hi, does someone knows about the bug, that the NSPersistentCloudKitContainer doesn't return CKShares at the first time? Is this an intended behavior? My current fix: let container: NSPersistentCloudKitContainer = .... // Fix begin let managedObject = .... // Object which is in a share let record = container.record(for: managedObject.objectID) // Fix end let shares = (try? container.fetchShares(in: nil)) ?? [] If I execute exactly the same code without the fix that I fetch the record first, then it returns 0 shares. With the fix it is currently 9 shares (the actual count of the shares). Another fix: let container: NSPersistentCloudKitContainer = .... // Fix begin let _ = try? container.fetchShares(in: nil) Thread.sleep(forTimeInterval: 0.1) // Fix end let shares = (try? container.fetchShares(in: nil)) ?? [] For that fix it also returns at the second time the expected count of shares. But without the delay it returns also at the second time zero shares. Anyone had the same problem and if so, how do you solve it correctly? Thanks!
0
0
138
6d
What does EXC_CRASH (SIGILL) mean?
We started to see some crashes in our iOS app a few seconds after launch with the following reason: Exception Type: EXC_CRASH (SIGILL) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: SIGNAL 4 Illegal instruction: 4 when calling [NSPersistentContainer loadPersistentStoresWithCompletionHandler:]. I've looked through Understanding the exception types in a crash report page, but couldn't find this type there. Any ideas what could it be?
5
0
227
1w
Huge increase in sqlite file size after adopting CloudKit
I recently converted a Core Data app to use CloudKit. Before the conversion, the sqlite file was around 25MB. After the conversion, the file grew to over one gigabyte. I ran sqlite3_analyzer on the new file and found that a single table, ANSCKRECORDMETADATA, used 95% of the storage, 998MB. Is this to be expected? I confess that the conversion was a bit bumpy. Maybe I did something to create a monstrosity. If not expected, should I revert to the old Core Data file, create a new CloudKit container, and repeat the conversion.
0
0
124
2w
Curious Synchronisation issue with Core Data
My app uses Core Data to store an synchronise the data. It runs on iOS, iPadOS and now WatchOS. The records are stored in the private and shared CloudKit database. Running the app in developer mode, syncing is fine for all devices. But as soon as I switch to production mode using TestFlight, the Watch only syncs the data of the shared records, while iPad and iPhone still are syncing all records (private and shared) correctly. I run out of ideas where to search for the reason of this problem. I use one module to setup the persistent store for iOS, iPadOs and WatchOS. Any ideas are well come.
2
0
108
2w
Restart sync when using NSPersistentCloudKitContainer
It's 2024, and it still seems like the only sure way to cleanly restart cloud sync on an app using NSPersistentCloudKitContainer is to uninstall and reinstall the app. No need to describe how bad that solution is... Am I missing something? Is there a better way to safely trigger such a restart of the sync (even if it means losing unsaved data and overwriting with what's in the cloud - which is what a reinstall does anyway)?
0
0
149
2w
Data storage for Network Extension
Hi, I have been working on some kind of network filtering app for iOS using Content Filter Provider. And I have stored rules for each domain. As of right now, I use UserDefaults with my app's bundle suite to store and observe rules. I have also read this documentation page for UserDefaults link. Is it okay to use UserDefaults in my case, if I have rules added/modified dynamically as the flow is intercepted, or should I pick some other approach like Core Data, SwiftData, etc.? Thank you!
15
0
438
2w
How do I resolve conflicts with SwiftData?
SwiftData includes support for CloudKit sync. However, I don't see any way to add conflict resolution behavior. For example, if different devices set different values for a field, or if a relationship is orphaned because of a deletion on another device, the application has to handle this somehow. In Core Data (which SwiftData wraps), you can handle this with the conflict resolution system (docs) and classes like NSMergePolicy. Is any of this accessible in SwiftData? If not, how do you deal with conflicts when syncing a SwiftData model with the cloud?
2
0
229
2w
Persisting Color from ColorPicker
Has anyone successfully persisted Color, particularly in SwiftData? So far my attempts have failed: Making Color conform to Codable results in a run time error (from memory something about ColorBox). Color.Resolved already conforms Codable but this results in "SwiftData/ModelCoders.swift:124: Fatal error: Composite Coder only supports Keyed Container" None of the other color types conform to Codable (CGColor, NSColor and UIColor) so does the swift language really not have a persistable color type?
2
0
251
3w
NSPersistentCloudKitContainer migration with custom NSEntityMigrationPolicy
Recently, I have made quite extensive changes to my schema and need to migrate my CoreData + CloudKit model to a new version. The changes require me to use a custom NSEntityMigrationPolicy because I have a rather complex mapping between some old entities and new entities. I have added a new model version. Deleted some entities, and added some entities. I have defined the NSEntityMigrationPolicy with createDestinationInstances(forSource:in:manager:) and createRelationships(forDestination:in:manager:). I have created a new Core Data Mapping Model. This was probably unnecessary. Within the Core Data Mapping Model, I have specified Custom Policy for all entities. In my container setup, I added two options, as below: storeDescription.setOption(false as NSNumber, forKey: NSMigratePersistentStoresAutomaticallyOption) storeDescription.setOption(false as NSNumber, forKey: NSInferMappingModelAutomaticallyOption) I mostly followed a "Core Data Heavyweight Migration" guide. I'm unable to share the link, but it can be quite easily found on the web. (It's not for CloudKit specifically.) When I run my app, I am getting the most basic of errors, which is: The managed object model version used to open the persistent store is incompatible with the one that was used to create the persistent store. So I guess that migration wasn't even attempted, which makes sense because I set NSMigratePersistentStoresAutomaticallyOption to false. I tried to go beyond what I could find on the web and attempted to manually initialize migration: let sourceModel = container.persistentStoreCoordinator.managedObjectModel guard let modelURL = Bundle.main.url(forResource: "MyModelName", withExtension: "xcdatamodeld") else { fatalError("Unable to locate model file.") } guard let destinationModel = NSManagedObjectModel(contentsOf: modelURL) else { fatalError("Unable to load destination model.") } let migrationManager = NSMigrationManager(sourceModel: sourceModel, destinationModel: destinationModel) let mappingModel = NSMappingModel(from: [Bundle.main], forSourceModel: sourceModel, destinationModel: destinationModel)! migrationManager.currentEntityMapping.entityMigrationPolicyClassName = "MyMigrationPolicyClassName" I am then stuck at the migrateStore(from:type:mapping:to:type:) method. It seems to target only local storage, not CloudKit. Otherwise, what do I provide for URLs and types? Any guidance for custom logic CoreData with CloudKit migration would be greatly appreciated.
1
0
156
3w
How to store Public Data in ICloud
I have been working on an ios application which I decided to use the new SwiftData architecture, and I now have realized that SwiftData does not support public or shared databases using SwiftData. I am a new and upcoming Swift developer, who has been self learning the Apple Swift technology. I just learned in this forum that Swift Data does not support Public and Shared Data and I also understand that no plans that have been announced to addressed this feature in the IOS 18 release time frame. The use case for my application is to implement a social type application, something like applications including X, facebook, etc. These type of applications appear to use Public, Shared and Private data in various existing Apple application. I would like to complete an application using Swift using ICloud, but I must assume that these current social applications are using other technologies. I am assuming you can do this in Core Data, but my understanding is Apple is asking that we use Swift Data to replace core data. I also am assuming that Swift data is built on core data technology layers. So ... to me it seems hopeful, somehow, to accomplish this using IOS 17 and follow the recommend Swift Data Path. What are my options for completing these data objectives in IOS? I hope I am addressing these questions in the proper and best forum? Much thanks for any suggestions.
2
0
191
3w
Can a private database entity have a relationship to a public database entity?
I’m using NSPersistentCloudKitContainer and I’m utilising the public database and also the user’s private database. For example I have an entity called Category which has a many-to-many relationship to an entity called NewsArticle. So the NewsArticles exist in the public database for the user to browse, but he can add them to a category which will live in his private database. So that’s my question, is it possible for an entity which exists a in the private database to have a relationship to another entity in a public database?
1
1
564
3w
Quicklook AugmentedReality Button Greyed-out
Hi, We are having problems with IOs Quick Look not working. Specifically, the AR button being greyed out after having opened the Scene / AR model previously. This is all running off our Web-App. What we have figured out is clearing the device's cache solves the issue and the greyed out button turns blue and clickable again. We are receiving this issue very inconsistently though - on iPad as well as iPhone and on both newer and older IOs versions. Very happy for any responses and advice to solve this issue as its behaviour makes the quick look function - even if it's great (when it works) unviable for Production (because it doesn't work consistently). Best Regards
0
0
160
3w
Differentiate whether NSPersistentStoreRemoteChange notification is coming from Cloud or a local change
How can we identify whether the remote change notification is triggered because some data was changed on a different device and it is downloaded from CloudKit, or it is triggered from the current device because new entity was saved into database. Because this notification is posted when both remote data is downloaded or local data is created. It would be great if there is a way to understand the origin of the notification.
0
0
193
4w
Unable to load CloudKit CoreData Store
I have a CoreData model, in a Swift Package with tests. I can successfully run the tests, when I load the model using NSPersistentContainer, however attempting this with NSPersistentCloudKitContainer always fails in the call to loadPersistentStores(completionHandler block: @escaping (NSPersistentStoreDescription, Error?) -> Void) The error is : [CK] BUG IN CLIENT OF CLOUDKIT: Not entitled to listen to push notifications. Please add the 'aps-connection-initiate' entitlement. This issue is described on StackOverflow however, the accepted solution does not appear to work in my case. I have tried adding the aps-connection-initiate key to my App Info.plist, the Test Info.plist and the SPM bundle. No change. (NB. adding this to the entitlements file just breaks auto signing). I have enabled App entitlements for App Groups, Remote Notifications background mode, Push Notifications and iCloud CloudKit with a store identifier. I have checked my model. All relationships have inverses. No unique constraints, etc. etc. I am sharing a Bundle ID with a previous version of the App, that also uses CoreData+CloudKit, each version has it's own Model and container identifier, each container identifier is available in the provisioning profile. The new version of the model has two NSPersistentStoreDescriptions, one is configured for CloudKit, the other is a local cache. I am completely stuck, suggestions would be very welcome.
3
1
1.3k
May ’24
SwiftUI NavigationLink freezing when tapped
Any one getting any issues with NavigaitonLink to seemingly innocuous views freezing when tapped on? 1 CPU at 100% memory steadily increasing until app gets killed by the system. Will freeze if any NavigationLink on the view is tapped if certain views are linked to using NavigaitonLink. I note some people have been getting similar freezes if they use @AppStorage, but I'm not using @AppStorage. I do use CoreData tho. tho I have some views that use core data that don't freeze. https://developer.apple.com/forums/thread/708592?page=1#736374022 has anyone experienced similar issues? or know the cause. it doesn't seem to be any of my code because if I pause the debugger it stops on system code.
11
2
5.3k
May ’24