I have recently moved some of my data save operations from the view context to background contexts. Since the switch, some (but not all) of my users are reporting that the background save operations crash 100% of the time. After researching, I have narrowed it down to the fact that these save operations involve establishing a relationship to an entity with a derived attribute. An example is shown below: try await CoreDataStack.shared.performBackgroundTask { context in var transaction = Transaction(context: context) transaction.amount = NSDecimalNumber(decimal: 0) transaction.id = UUID() let account = Account.account(withName: Default, in: context) transaction.account = account try context.save() } // <= Crashes! In the above example, each Transaction has a to-one relationship to an Account, and the latter has a to-many relationship the the former. Account has a derived attribute called balance that is calculated using the expression sum:(transactionItems.amount). The would then crash when the performBackgr
Search results for
NSPersistentCloudKitContainer
589 results found
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
There is an eventChangedNotification on NSPersistentCloudKitcontainer. You can add a notification/listener to your view/Observable class and re-fetch data like so: import CoreData import SwiftData import CloudKit @Observable class ListViewModel { var cloudkitNotificationPublisher = NotificationCenter.default.publisher(for: NSPersistentCloudKitContainer.eventChangedNotification) func handleCloudkitNotification(_ notification: NotificationCenter.Publisher.Output) { if let userInfo = notification.userInfo, let event = userInfo[NSPersistentCloudKitContainer.eventNotificationUserInfoKey] as? NSPersistentCloudKitContainer.Event { if event.type == .import { // fetch entities/models here } } } } And then in your view, you can attach an .onReceive(_:) modifier to your view, passing in the publisher var body: some View { VStack { // my list here } .onReceive(listViewModel.cloudkitNotificationPublisher) { publisher in listViewModel.handleCloudkitNotification(publisher) } } More information can be found here: ht
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
Hi all, I have an iOS app which uses CloudKit and the standard NSPersistentCloudKitContainer, which I rely on for syncing app data between the user's devices. If the user's iCloud account is full I can see a log message while debugging in Xcode shortly after startup which looks something like this: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2183): - Never successfully initialized and cannot execute request ' 51383346-87BA-44D8-B527-A0B1EE35A0EF' due to error: 2FC9A487-D630-444D-B7F4-27A0F3A6B46E:(com.apple.coredata.cloudkit.zone:__defaultOwner__) = 903DD6A0-0BD8-46C0-84FB-E89797514D9F:(com.apple.coredata.cloudkit.zone:__defaultOwner__) = }> I would like to know how I can get a callback of some sort so I can run code if this CloudKit/CoreData error happens. In particular I'd like to put up some sort of warning to the user letting them know their data isn't going to sync. Please note that I'm not looking for how to do error handling as a result of a u
I’ve setup the Cloudkit persistent container with private and shared database (see code below). I’ve enabled NSPersistentHistoryTrackingKey to true also for .shared database. I’ve noticed in the example from Apple that the History Tracking is only enabled in .private but not for .shared. Questions: For a CloudKit setup to sync (a) between owners’ own devices (only private database), and (b) between multiple iCloud Users through .private and .shared databases, Do I need to enable history tracking for .shared database if I want to check the remote changes in the .shared database (or is the history tracking of the .private database of the owner also accessible in the .shared database)? ======================== let APP_BUNDLE_IDENTIFIER = Bundle.main.bundleIdentifier! let APP_GROUP_IDENTIFIER = group. + APP_BUNDLE_IDENTIFIER private func setupPersistentContainer(_ container: NSPersistentCloudKitContainer? = nil, isStartup: Bool = true) -> NSPersistentCloudKitContainer { let container = contai
First, I’d like to be clear about the behavior NSPersistentCloudKitContainer implements when you use it to share a managed object (NSManagedObject) so we are on the same page: When you save object A to the Core Data store associated with the private database, NSPersistentCloudKitContainer transforms the object to a CloudKit record A, and synchronizes it to the record zone 1 in the CloudKit private database, with zone ID being com.apple.coredata.cloudkit.zone. When you then use NSPersistentCloudKitContainer.share(_:to:completion:) to create a new share (CKShare) and share object A to another user, NSPersistentCloudKitContainer moves record A to a record zone 2, with zone ID being com.apple.coredata.cloudkit.share. . Note that zone 2 is still in the private database. What you call NSPersistentCloudKitContainer.share(_:to:completion:) with an unsaved managed object A. Core Data saves the object for you, and the associated record A will be saved to zone 2. Regarding Core Data relationsh
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
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,
sample code let modelConfiguration = ModelConfiguration() // 1. create mom guard let mom = NSManagedObjectModel.makeManagedObjectModel(for: [Attachment.self]) else { fatalError(====> makeManagedObjectModel error) } // 2. create description with config url and setting let description = NSPersistentStoreDescription(url: modelConfiguration.url); description.shouldAddStoreAsynchronously = false; container = NSPersistentCloudKitContainer(name: swiftDataCloudTest, managedObjectModel: mom); container.persistentStoreDescriptions = [description] // 3. get modelContainer let modelContainer = try! ModelContainer(for: Attachment.self, configurations: self.modelConfiguration) this code works fine on MacOS(14.4.1) and previous iOS 17.x.(iOS 17.2 is OK) but on iOS 17.5, the app crashes with message A Core Data error occurred. UserInfo={NSLocalizedFailureReason=Unable to find a configuration named 'default' in the specified managed object model how can I fix these?
@Engineer Hi, Sorry for many questions - still can't figure out why crash happens in widget extension. I was curious, if it can be connected to the usage of NSPersistentCloudKitContainer? Would appreciate any help of advice. Thanks in advance!
Topic:
Developer Tools & Services
SubTopic:
Xcode
Tags:
I'm currently syncing core data with the CloudKit private and public databases, as you can see in the code below, I'm saving the private database in the default configuration in Core Data and the public in a configuration called Public everything works fine when NSPersistentCloudKitContainer syncs, what I'm having an issue with is trying to save to the public data store PublicStore, for instance when I try to save with func createIconImage(imageName: String) it saves the image to the default store, not the PublicStore(Public configuration). What could I do to make the createIconImage() function save to the PublicStore sqlite database? class CoreDataManager: ObservableObject{ 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() }()
I’ve considered turning textString into a to-many relationship by creating a Token entity but I’m unsure whether this will significantly increase overhead? I expect my database to grow very large unless I apply unique constraints on tokens and handle the CloudKit syncing myself (not using NSPersistentCloudKitContainer). Also in my app if many results are fetched (between 1000 to 100,000 matches) from the predicate I will need to perform an additional filter that can only be done in-memory, in this scenario would I need to perform both the predicate and filter in batches?
Topic:
Community
SubTopic:
Apple Developers
Tags:
Hello, I have an iOS app and a companion watchOS app. Users record a workout on Apple Watch, the data for which is then transferred using both Watch Connectivity and Core Data + CloudKit (NSPersistentCloudKitContainer) to their iPhone, where it is processed and displayed. As users are recording the workout on their Apple Watch, when they finish and the transfer begins, their iPhone is often not reachable to immediately send the data using Watch Connectivity and they have no network connection (cellular or Wi-Fi). With Watch Connectivity I use transferFile from WCSession, which queues the file for transfer. With Core Data + Cloudkit I save the data and the export is queued. An undetermined amount of time may pass until the user returns to their iPhone or connects to Wi-Fi and most of the time neither of the transfer methods actually transfers the data until the user opens the watchOS app into the foreground, at which point the transfer happens immediately for both methods. I've tried a number of thing
Topic:
App & System Services
SubTopic:
Core OS
Tags:
Watch Connectivity
CloudKit
watchOS
Background Tasks
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:
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)?
I'm currently syncing Core Data with the CloudKit public database using NSPersistentCloudKitContainer. The app starts with an empty Core Data store locally and at the app launch it downloads the data from CloudKit public database to the Core Data store, but this can only be accomplished if the user is logged in, if the user is not logged, no data gets downloaded and I get the error below. Can the NSPersistentCloudKitContainer mirror the data from the CloudKit public database to the local Core Data even if the user is not logged in? Can someone please confirm this is possible? The reason for my question is because I was under the impression that the users didn't need to be logged to read data from the public database in CloudKit but I'm not sure this applies to NSPersistentCloudKitContainer when mirroring data. I know I can fetch data directly with CloudKit APIs without the user beign logged but I need to understand if NSPersistentCloudKitContainer should in theory work with
Here is the code that works only if the user is logged in. Again, I'm connecting to the Public database. class CoreDataManager: ObservableObject{ // Singleton static let instance = CoreDataManager() private let queue = DispatchQueue(label: CoreDataManagerQueue) private var iCloudSync = true 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: CoreDataContainer) guard let description = container.persistentStoreDescriptions.first else{ fatalError(###(#function): Failed to retrieve a persistent store description.) } description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) let cloudKitContainerIdentifier = iCloud.com.example.PublicDatabaseTest let options = NSPersistentCloudKitContainerOptions(containerIdent
Topic:
Developer Tools & Services
SubTopic:
Xcode Cloud
Tags: