Search results for

NSPersistentCloudKitContainer

589 results found

Post

Replies

Boosts

Views

Activity

Reply to Initialising CloudKit schema on public database fails for in Core Data with multiple strings (rdar://FB8995024)
@Nick: Initialising against the private database as you suggested works on iOS 14.5. It would be really useful if that was in the documentation for initializeCloudKitSchema() if it's not likely to be fixed to support initialising against a public database, to avoid others falling into the trap I did! I've commented to that effect on FB8995024, too. On iOS 15, I can't verify if that's also the case yet because of FB9156476 (the feedback I created during our lab session). For the sake of anyone else who finds this thread, the error that feedback refers to is below. FB9156476 (iOS 15 NSPersistentCloudKitContainer can't sync initial data from server with “Failed to sync user keys”) error: 2021-06-10 21:51:53.672655+0100 MyApp[1230:15921] [error] error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(955): : Failed to set up CloudKit integration for store: (URL: file:///Users/steve/Library/Developer/CoreSimulator/Devices/59435252-2CF1-4980-8ABB-4B46B21385AA/data/Conta
Jun ’21
Reply to Sync an interactive widget's Core Data store with the main app (and iCloud)
The reason your main app doesn't update when your widget changes the shared store is most likely because the viewContext in your main app doesn't automatically detect and merge remote changes. Here, remote changes mean the changes made by a different process, or by using batch processing. Your main app can detect and handle remote changes in the following way: Observe the the .NSPersistentStoreRemoteChange notification to get notified of any remote change. In the notification handler, consume the store persistent history to detect the relevant changes and merge them to the managed object context tied to your main app UI. Alternatively, you can manage to reset the context, and then re-fetch, which should give you the up-to-date data. For more information about this topic, see the following Apple sample projects: Loading and Displaying a Large Data Feed. Sharing Core Data objects between iCloud users. Regarding using Core Data + CloudKit (NSPersistentCloudKitContainer) in an extension, I'd like to sugg
Mar ’25
Reply to NSPersistentCloudkItContainer and iCloud synchronization speed issues
Both methods experience delays when synchronizing a large amount of data at once. We are using two methods: During the initial installation, we call the below code to receive synchronization data and provide a user experience indicating that synchronization is in progress. public extension NSPersistentCloudKitContainer { func waitForCloudKitEvents(timeout: Int) async throws -> NSPersistentCloudKitContainer.Event? { let affectedStores = persistentStoreDescriptions .filter { description in description.cloudKitContainerOptions != nil } .compactMap { description -> NSPersistentStore? in guard let url = description.url else { return nil } return persistentStoreCoordinator.persistentStore(for: url) } let context = newBackgroundContext() let request = NSPersistentCloudKitContainerEventRequest.fetchEvents(after: .distantPast) request.resultType = .events request.affectedStores = affectedStores for seconds in 0...timeout { await Task.sleep(seconds: 1) let results: NSPersistentStoreResult = try context.e
Jan ’24
Reply to Value of type 'NSPersistentCloudKitContainerOptions' has no member 'shouldInitializeSchema'
For anyone else finding this:You need to call container.initializeCloudKitSchema() after container.loadPersistentStores.You don't really need to call container.initializeCloudKitSchema() at all, as CloudKit will create your schema on the fly. initializeCloudKitSchema just sends some fake data for your model, so it's handy to see if anything's going to break that Xcode didn't warn you about.Here's some code that works in Xcode 11 beta 5 to initialize an NSPersistentCloudKitContainer using a local store and a cloud store (see the Manage Multiple Stores section of the Setting Up Core Data doc). // MARK: - Core Data stack /// Convenience method so you can do DataManager.shared.context instead of DataManager.shared.persistentContainer.viewContext. lazy var context = self.persistentContainer.viewContext /// persistentContainer.viewContext lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loade
Aug ’19
Reply to How to fix NSCloudKitMirroringDelegate unhandled exception after faulty model change
One root cause that we have identified for this issue is removing a many-to-many relationship from your model. This is supposed to be a supported migration, so we are collecting feedback reports to track against that as a bug. If you would like to be notified of a fix for that share your feedback number here and we can relate them together. As a workaround you can simply add the relationship back. Or, attempt a more detailed / invasive solution described below. Our schema is public and described here: https://developer.apple.com/documentation/coredata/mirroring_a_core_data_store_with_cloudkit/reading_cloudkit_records_for_core_data Your container will contain CDMR records that identify the offending relationship. The fields CD_entityNames and CD_relationships can be used to tell which relationship a record represents. One (or more, depending on how many relationships you removed) of those records may be causing this issue. You can choose to: Add the missing relationship back to your model Delete the offending
Oct ’23
Reply to NSPersistentCloudkitContainer Memory Leak -> Crash? (iOS 15 beta 4 & 5)
This is all very confusing to me... ...and it's quite possible that this 'bug' is something I'm doing wrong when ingesting data from a backup file, despite it all appearing to save to Core Data just fine. But why now though? Why has it been working just fine for almost 2 years without modification? Backup Restore Process The backup file that my users create is a serialised dictionary file, which includes encoded data for images (if present). When I restore it, I use a private context to ingest it on a background thread, with a progress bar being updated on the main thread. As I do not want partially imported data to be incorporated into the user's Core Data store I only save the context at the end of the import when successful. This has been working flawlessly for the past 2 years with NSPersistentCloudKitContainer, with the data syncing after the import finishes and is saved to Core Data... but was it only working by accident all this time!? Should I not be using the private context to save imported
Sep ’21
Reply to iOS 17 Debug Log- Failed to convert from bundle ID
I’m seeing the same error on both Xcode 15.0 and Xcode 15.1 Beta. For me, I think this issue stemmed from NSPersistentCloudKitContainerOptions. I’m using NSPersistentCloudKitContainer in my app. If I set NSPersistentStoreDescription.cloudKitContainerOptions to nil, this error would go away. Of course my app can’t sync via CloudKit if I do that. Another issue may or may not related to this warning: ever since I built my app on Xcode 15, I’ve seen excessive disk read on the sqlite file of CoreData on launch. The amount of disk read can be as much as twice the size of the sql file, basically making the app impossible to use for some users with large data set. But if cloudKitContainerOptions is nil, this excessive disk read would disappear. Last issue may or may not related to this warning: the size of CoreData sqlite file in my app is 130 MB. But in iPhone Settings → [User Name] → iCloud → Manage Account Storage, it says my app takes up a whopping 2.7 GB of space. No matter how the calculation is done,
Oct ’23
Reply to CD4CK Syncing after long-term usage concerns
If I'm reading between the lines, after looking at Persistent History Tracking, I think the content will be downloaded in the order it was created. Although the single article, Consuming Relevent Store Changes, I read in the developer docs assumes some familiarity with the technology, which I have none, it doesn't actually mention iCloud or CloudKit. I still have to watch the WWDC video that introduces Persistent History Tracking, so I'm hoping What's New in Core Data 2017, answers a lot of questions, (although I don't have my hopes up considering it's pre-Core Data for CloudKit), because the Persistent History section in the documentation, is just an API reference with zero actual explanation of the technology. When I said my data model represents something like the macOS file system, I was implying it was an analogy. My app doesn't really have concrete directories or files. It's the tree structure I was trying to explain.My situation is slighly more complex than you might imagine, because of the seed data I
Sep ’19
Reply to Trigger data transfer from watchOS when connectivity is restored
There isn't, and I see that an as-designed behavior. When a file is queued for a Watch Connectivity transfer, or a change is queued for a Core Data + CloudKit export, it is up to the system to decide when the operation should happen. That is for optimizing the overall system performance, and there is no way for developers to change the behavior. This is documented in the following API reference and technote respectively: transferFile(_:metadata:): The system attempts to send files as quickly as possible but may throttle delivery speeds to accommodate performance and power concerns. TN3164: Debugging the synchronization of NSPersistentCloudKitContainer The goal of implementing such a mechanism is to balance the use of system resources and achieve the best overall user experience on the devices. There is no API for apps to configure the timing for the synchronization. So even you have your watchOS app run in the background (for a period of time) using something like background workout processing or Hea
Topic: App & System Services SubTopic: Core OS Tags:
Jul ’24
Reply to SwiftData - Cloudkit stopped syncing
In CloudKit development environment, when your app creates a record, CloudKit automatically creates the record type, if it doesn’t exist. With that, if you ever persist (at least) an instance for each of your SwiftData type, and the instance is pushed to CloudKit, the CloudKit schema will have the record type for you. Otherwise, the record type will be missed. initializeCloudKitSchema(options:) works by creating a set of representative records, uploading them to CloudKit, and removing them. This may help if it is indeed that no instance of your new SwiftData type has ever been uploaded to CloudKit. Note that even initializeCloudKitSchema(options:) can miss something, and that is why I called out the following: After running the target, use CloudKit Console to ensure each Core Data entity and attribute has a CloudKit counterpart. See Reading CloudKit Records for Core Data for the mapping rules. The documentation discusses how NSPersistentCloudKitContainer maps a Core Data model to a CloudKit schema,
Sep ’25
Reply to Check Data Re-Sync on App Reinstall with CloudKit (+SwiftUI)
I'm using an almost identical CoreData stack as to what was shown in the WWDC 2019 Posts demo app. Here's the code: import Foundation import CoreData // MARK: - Core Data Stack /** The main Core Data stack setup including history processing./ class CoreDataStack { tt/** ttttA persistent container that can load cloud-backed and non-cloud stores. tt */ ttlazy var persistentContainer: NSPersistentCloudKitContainer = { tttt tttt// Create a container that can load CloudKit-based stores ttttlet container = NSPersistentCloudKitContainer(name: MyCoreDataApp) tttt tttt// Enable history tracking and remote notifications ttttguard let description = container.persistentStoreDescriptions.first else { ttttttfatalError(###(#function): Failed to retrieve a persistent store description.) tttt} ttttdescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) ttttdescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) tttt ttttcontainer.loadPer
Jun ’20
Reply to Restart sync when using NSPersistentCloudKitContainer
With the following code I'm successfully turning On or Off sync between CoreData and CloudKit. I have iCloudSync saved in UserDefault / @AppStorage and controlled with a toggle switch in my app settings. This line is what turn it off description.cloudKitContainerOptions = nil, I hope it helps. class CoreDataManager: ObservableObject{ // Singleton static let instance = CoreDataManager() private let queue = DispatchQueue(label: CoreDataManagerQueue) @AppStorage(UserDefaults.Keys.iCloudSyncKey) private var iCloudSync = false lazy var context: NSManagedObjectContext = { return container.viewContext }() lazy var container: NSPersistentContainer = { return setupContainer() }() func updateCloudKitContainer() { queue.sync { container = setupContainer() } } func setupContainer()->NSPersistentContainer{ let container = NSPersistentCloudKitContainer(name: YourCoreDataContainerName) guard let description = container.persistentStoreDescriptions.first else{ fatalError(###(#function): Failed to retrieve a persis
Jun ’24
Reply to How to read/write to App1’s database from App2?
OK, I've solved my issue. 1st of all, defining 2 NSPersistence : ObservableObjects most definitely wasn't the way to go: @StateObject var app1DB = PersistenceApp1.shared @StateObject var app2DB = PersistenceApp2.shared I just needed one: @StateObject var persistence = Persistence.shared deeje's answer pointed me in the right direction, but what was still missing for me were the following 3 key ideas: container's name: is just the name of the .xcdatamodeld - and that this has nothing to do with what I expected (ie, that it was somehow related to my CloudKit container ids “iCloud.com.company.App1”) container = NSPersistentCloudKitContainer(name: Model) Within Model.xcdatamodeld I needed to define 2 separate configurations - with each configuration holding the Entities that are held within the the CloudKit containers: App1Config - holds the Entity from iCloud.com.company.App1, and App2Config - holds the Entity from iCloud.com.company.App2 I needed 2 store descriptions for each app, and to specify the sq
Topic: UI Frameworks SubTopic: SwiftUI Tags:
Sep ’22
How to save an audio file using Core Data + CloudKit?
I am transitioning to using CloudKit for syncing, using NSPersistentCloudKitContainer to manage syncing. In my app you can record audio, and I've been saving that by saving the file to disc and storing a relative URL to Core Data. How can I get this to work using NSPersistentCloudKitContainer? I read that I shouldn't store large data as a CoreData attribute for performance, but I need the data to sync with CloudKit.
1
0
1.3k
Feb ’21
Reply to WidgetKit and CoreData/CloudKit
In testing today, syncing in the background with NSPersistentCloudKitContainer seems to be working more reliably with the iOS 16 SDK. The first time you change something on another device it still seems to schedule a task to perform that work with utility priority (via -[NSCloudKitMirroringDelegate checkAndScheduleImportIfNecessary:andStartAfterDate:] which logs Scheduling automated import with activity CKSchedulerActivity priority 2 Utility), so it doesn't execute right away. If you change it again then I'm seeing it does immediately import the two accumulated changes (NSCloudKitMirroringDelegate Beginning automated import - ImportActivity - in response to activity, then -[PFCloudKitImportRecordsWorkItem applyAccumulatedChangesToStore:inManagedObjectContext:withStoreMonitor:madeChanges:error:] followed by NSCloudKitMirroringImportRequest Importing updated records) which triggers NSManagedObjectContextObjectsDidChange, NSPersistentStoreRemoteChange, and NSPersistentCloudKitContainer.eventChangedNotif
Jun ’22