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

iCloud container Mac App Question About Moving Files: Is a File Coordinator Necessary?
In NSFileManager there is this method to move files to and from iCloud:- (BOOL)setUbiquitous:(BOOL)flag itemAtURL:(NSURL *)url destinationURL:(NSURL *)destinationURL error:(NSError **)errorOutAll the samples and information I'm able to find seem to be related to using NSDocument, which my app isn't using. I have a little view in my app that allows users to move an image out from the iCloud container and into a local directory. It seems that simply using NSFileManager moveItemAtURL:toURL:error: works fine both to move a file in and out of the iCloud container on OS X without wrapping everything in a file coordinator block. Is it still necessary to use a file coordinator to move files out of iCloud on the Mac. When I put a file in the iCloud container, the system automatically starts uploading it..even though I'm not using a file coordinator...and my related file presenter still is detecting a change.Both methods seem to be working the same, I'm just wondering if I should be using a coordinator because it's a good amount of code I can get rid of if it's not necessary.Thanks.
1
1
573
Aug ’15
ckSession instead of ckWebAuthToken
Hello.I am starting working with theCloudKit Web ServicesI am reading the documentation here:https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/CloutKitWebServicesReference/SettingUpWebServices/SettingUpWebServices.html#//apple_ref/doc/uid/TP40015240-CH24-SW1I am trying to receive Getting the Web Authentication TokenAfter successfully login I am getting this jsonObject appInfo:Object AdditionalSalt:"cec2731125ded8d34cbd3702e0c360b8b7b534fa04dbb2f0ea150b524b7739e5"AppDiscoverable:"false"AppId:"0"AppName:"iCloud.jovan.PhotoWebApp"ContainerEnvironment:"development"ContainerId:"iCloud.jovan.PhotoWebApp"DeveloperName:"UNKNOWN_DEVELOPER"LogoURL:""__proto__:ObjectckSession:"48__24__AZLhIol7ffB34oNYrGP54rWKY5MiVdO+2+85oIiWPuKoK/KJ7r9cNivNwYd03iX/aDW6KL4wuAOVJZ0dAShqhT9ZhoUuW9ZZNPPQ7tzTcBNJ/itQI/uulkBi/51Rpijv/5ZypUYD9yGP3dyXQgDVlGSK8tUPHigigN7nO91DGkM1kaT11lXFBBCHlvZr0DX4tp1cxZ9/P/Q=__eyJYLUFQUExFLVdFQkFVVEgtUENTLUNsb3Vka2l0IjoiUVhCd2JEb3hPZ0VpWXd2Q0QyYmdCVWZrblo1cmp3dnl3Wjg1cHF1dTdLaFZPMThnMEx1bDhLeWRhMHR5SkhyUkZwT0JycEVicXNXWGhqUk9XbTlyd2pkZzB6K3JvZktOIiwiWC1BUFBMRS1XRUJBVVRILVBDUy1TaGFyaW5nIjoiUVhCd2JEb3hPZ0ZyZzEyZGNZSGk4WWRKYU0yK1pFMFRKaytrdTBBMmNZTG8vaUJPRlV1cEtKT3ExS1YvYjlBaldCeklwQTR5N2FUbXNrMDhCWjRsYVRoeWRTaSt3eE9PIn0="isICDP:falsepcsDeleted:falsepermissions:Array[1] 0:Object ask:falsename:"discoverability"__proto__:Objectlength:1__proto__:Array[0]status:0But, as per documentation I should receive the ckWebAuthToken instead of ckSessionCould you please help me? Looks like documenttion is incorrect or i do something wrong...How to get the ckWebAuthToken or how to use this ckSession for requesting the web services?
2
0
1.2k
Sep ’16
Error accepting CKShare
Hello,I am creating a new app that uses CKShare. I am able to create the CKShare and send it by email using UICloudSharingController.When the receiver of the invite tries to accept the share, there is an error message"Couldn't open "Title"You need a newer version of "App" to open this, but the required version couldn't be found in the App StoreMy app has not been published to app store yet. How do I resolve this error? I am using a development build with two apple id's to test ckshare.Thanks!
3
0
2.0k
Jan ’17
iOS NSCoreDataCoreSpotlightDelegate, how to reindex all items
I have implemented NSCoreDataCoreSpotlightDelegate, and I missed out the part where the default expirationDate is 1 month, now items that I have added 3 months ago are not showing up in the search index.How do I get NSCoreDataCoreSpotlightDelegate to reindex all the items?I used to be able to call this:mcdcsd.searchableIndex(CSSearchableIndex.default(), reindexAllSearchableItemsWithAcknowledgementHandler: {})And the first time, it will reindex all the items, but if I re-run the app with the above line uncommented again, it will not reindex.If I uninstall the app, install back, then uncomment the above line, then it will index all again for the first time.How do I get it to reindex everything again?
2
0
1.7k
Apr ’19
CD4CK: Can't find Default configuration in M.O.M.
There are a few things about how Core Data 4 Cloud Kit initializes that I'm stuggling to understand. I've spent most of the day finally getting a schema initialized on the server, and learnt a few things along the way.Firstly, even though I have a Default configuration in my managed object model, and it has been there from day one with the option "Used with CloudKit" checked for true, if I create an `NSPersistentStoreDescription` and set the configuration property to "Default", when I try to load the stores, it will fail, saying "Unable to find a configuration named 'Default' in the specified managed object model.". If I inpsect the debug description for my ManagedObjectModel instance, it does indeed not have any reference to the string "Default" in it (I'm not sure if debugDescription is actually printing out the configuration names however). Why does this fail? I can only get my store loaded and the schema initialized if I remove the code that sets the configuration name to "Default".The next thing that tripped me up was the NSPersistentCloudKitContainerOptions property on the store description. Considering that the only property on that class is now gone, so you no longer need to perform `options.shouldInitializeSchema = true`, I incorrectly assumed that I'd no longer need to even create and set a NSPersistentCloudKitContainerOptions instance on my store description, because all it really holds is the containerIdentifier. Why would I need to specify a container identifier if the system is going to fetch the first iCloud Container Identifier out of the entitlements file and associate it with the Default configuration which I'd (clearly incorrectly) assumed would be automatically associated with CloudKit and my "Default" entitlement container identifier.Below is the code I was using. It's mild playground refactor of my real code, but it's quite straightforward.// Instantiate the Managed Object Model let modelName = "CloudModel" let url = Bundle.main.url(forResource: modelName, withExtension: "momd") let mom: NSManagedObjectModel = NSManagedObjectModel(contentsOf: url!)! // Define the Cloud Store Description let storeURL = URL(fileURLWithPath: "Cloud.sqlite", isDirectory: false, relativeTo: NSPersistentContainer.defaultDirectoryURL()) let cloudStoreDescription = NSPersistentStoreDescription(url: storeURL) cloudStoreDescription.shouldAddStoreAsynchronously = true cloudStoreDescription.configuration = "Default" // this will cause loading to fail with an "Unable to find // a configuration named 'Default' in the specified managed object model." error // Add a container options instance to the description, because without it, loading will fail with // "Couldn't initialize CloudKit schema because no stores in the coordinator are configured to use CloudKit" var cloudKitOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "com.example.container.identifier") cloudStoreDescription.cloudKitContainerOptions = cloudKitOptions // Create the Container for the Cloud Store let container: NSPersistentCloudKitContainer = NSPersistentCloudKitContainer(name: modelName, managedObjectModel: mom) container.persistentStoreDescriptions = [cloudStoreDescription]
2
0
1.4k
Aug ’19
CoreData+CloudKit Model Migration Failing
So I've been developing happily with CoreData+CloudKit for a while now, and really haven't run into any issues until this. I've migrated my model a couple of times, and it worked fine, but this was the first time I added a new entity to the model. If I run on a device (any device, iPhone, iPad, Mac via Catalyst), I get a migration error. Here's the entirety of my persistentContainer setup: public var persistentContainer: NSPersistentContainer = { let modelPath = Bundle(for: CoreDataStack.self).url(forResource: "Progress", withExtension: "momd")! let model = NSManagedObjectModel(contentsOf: modelPath)! let container = NSPersistentCloudKitContainer(name: "Progress", managedObjectModel: model) container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { print(storeDescription) fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }()And here's the error I'm getting:Callstacks=true}}}CoreData: annotation: : Attempting recovery from error encountered during addPersistentStore: Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration." UserInfo={sourceURL=[…].sqlite, reason=Cannot migrate store in-place: constraint violation during attempted migration, destinationURL=[…].sqlite, NSUnderlyingError=0x600000cebae0 {Error Domain=NSCocoaErrorDomain Code=134111 "(null)" UserInfo={_NSCoreDataOptimisticLockingFailureConflictsKey=( ), NSUnderlyingException=Constraint unique violation, reason=constraint violation during attempted migration, NSExceptionOmitCallstacks=true}}}Important note: I am not using contraints at all in this model. I have created a new Entity, given it a single attribute, and a single one-to-many relationship with an existing entity. That's all.Also, here's an excerpt from the logs when I have -com.apple.CoreData.MigrationDebug enabled, pointing to an issue with the CloudKit metadata tables update step:CoreData: annotation: Completed persistent history metadata tables update CoreData: annotation: Beginning CloudKit metadata tables update CoreData: annotation: Failed lightweight migration on connection CoreData: annotation: Rolling back formal transactionAnyone seen this, have any idea what could be failing, or how to make cloudkit/coredata happy with a migration like this?
10
3
4.6k
Jun ’20
CoreData: warning: CoreData+CloudKit
I use NSPersistentCloudKitContainer. It seems that it the data synced in iCloud after a few seconds. However, I get the following warnings in the console. I do not understand what is it for. CoreData: warning: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(813): &lt;NSCloudKitMirroringDelegate: 0x280b051e0&gt;: Successfully set up CloudKit integration for store: &lt;NSSQLCore: 0x280024a00&gt; (URL: file:///private/var/mobile/Containers/Shared/AppGroup/89D9D17C-03DF-48E4-83C3-DB23A8FE0D6F/TestData.sqlite) CoreData: warning: CoreData+CloudKit: -[NSCloudKitMirroringDelegate checkAndScheduleImportIfNecessary:]_block_invoke(2033): &lt;NSCloudKitMirroringDelegate: 0x280b051e0&gt;: Scheduling automated import with activity: <CKSchedulerActivity: 0x281f51590; additionalXPCActivityCriteria={     Priority = Utility; }, containerID=&lt;CKContainerID: 0x283c612e0; containerIdentifier=iCloud.io.test.testData, containerEnvironment="Sandbox"&gt;, identifier=com.apple.coredata.cloudkit.activity.import, priority=2> Could you please explain what is this warning for and what should I do to fix it?
2
0
1.4k
Jul ’20
[NSPersistentCloudKitContainer] CloudKit integration forbids renaming 'OldEntityName' to 'NewEntityName'. Older devices can't process the new records. How to proceed?
I used a renaming identifier to rename an Entity Name, but it doesn't seem to work and it causes a crash at start during in-place migration. How to rename an Entity Name when using NSPersistentCloudKitContainer? I get this exception at start: CloudKit integration forbids renaming 'OldEntityName' to 'NewEntityName'. Older devices can't process the new records. Unresolved error Error Domain=NSCocoaErrorDomain Code=134110 "An error occurred during persistent store migration." App is not in production, need a way to rename 'OldEntityName' to 'NewEntityName'. How to achieve this?
1
1
698
Sep ’20
CloudKit and Background tasks
Hi. Didn't find the answer in the documentation. Are CloudKit procedures executables in background tasks ? I'm trying to do : "[privateDatabase fetchRecordWithID:myMasterRecordID completionHandler:^(CKRecord *myMasterRecord, NSError *error) { ... }]" but it returns a record only when the app is active. In background task, it does nothing and waits until app is active. Thanks for you answer. Best Claude
1
0
736
Jan ’21
Core Data and Relationships
I've a large data feed to load in database. this data populate many entities that are related each others. I've follow this official tutorial - https://developer.apple.com/documentation/coredata/loading_and_displaying_a_large_data_feed to use nsbatchInsertRequest. But this tutorial has one big bug: populate data only in one entity. How many apps use a database with only one entity? therefore the problem that I have not only me, but several people, is time. With nsbatchinsertrequst I was able to insert more than 30000 records in just 5 seconds with a use of just 25MB of RAM. But without setting up relationships. if after the execution of the various insertrequests I set the relations, everything takes me about 50 seconds with an increase in memory to 60-70 MB. Is it possible that there is no way to quickly set up relationships? Not only that, this is a forum where Apple engineers, who therefore know the subject better, should give help. but who knows why, for such questions they disappear. Maybe it's my posts that are so boring that Apple ignores them? Or are they so difficult that even apple engineers can't solve them? Who knows if I'll ever find the answer! But is it possible that they don't have a solution? These Apple engineers if they had the same problem as me, how would they solve it? they simply say: "it can't be done! Arrange!"? anyway, I hope that some Apple engineer or someone experienced will be able to find the solution at least to this problem. Or it will be another zombie post in the billions of zombie posts of people like me who pay $ 100 but get no support. Thank you
2
1
1.4k
Feb ’21
Manually define a CKRecord ID for a given NSManagedObject instance
I have an app that is already running with CoreData, and I want to allow the users to upload their data to iCloud so, in the case they need to delete their apps or change devices, they don't lose it. Every time the app is opened, there is a synchronization that happens between CoreData and a JSON file fixture, in order to fill the app with its base values (creating NSManagedObject instances from the aforementioned fixture). Before the iCloud sync, the CoreData model had some constraints for different entities, to enforce uniqueness, but these had to be stripped since CloudKit doesn't support them. Most of these constraints were basically ids that came from the JSON and represent an item in our Firebase database. Given that, I want to make the underlying CKRecord.id the same as these ids, so I can avoid the situation where, if a person open the app in a second device, the fixture data is repeated, since the fixture runs before the sync with the iCloud happens. Is that possible? Any help would be appreciated.
6
0
1.3k
Jul ’21
NSPersistentCloudkitContainer Memory Leak -> Crash? (iOS 15 beta 4 & 5)
Background I have an established app in the App Store which has been using NSPersistentCloudkitContainer since iOS 13 without any issues. I've been running my app normally on an iOS device running the iOS 15 betas, mainly to see problems arise before my users see them. Ever since iOS 15 (beta 4) my app has failed to sync changes - no matter how small the change. An upload 'starts' but never completes. After a minute or so the app quits to the Home Screen and no useful information can be gleaned from crash reports. Until now I've had no idea what's going on. Possible Bug in the API? I've managed to replicate this behaviour on the simulator and on another device when building my app with Xcode 13 (beta 5) on iOS 15 (beta 5). It appears that NSPersistentCloudkitContainer has a memory leak and keeps ramping up the RAM consumption (and CPU at 100%) until the operating system kills the app. No code of mine is running. I'm not really an expert on these things and I tried to use Instruments to see if that would show me anything. It appears to be related to NSCloudkitMirroringDelegate getting 'stuck' somehow but I have no idea what to do with this information. My Core Data database is not tiny, but not massive by any means and NSPersistentCloudkitContainer has had no problems syncing to iCloud prior to iOS 15 (beta 4). If I restore my App Data (from an external backup file - 700MB with lots of many-many, many-one relationships, ckAssets, etc.) the data all gets added to Core Data without an issue at all. The console log (see below) then shows that a sync is created, scheduled & then started... but no data is uploaded. At this point the memory consumption starts and all I see is 'backgroundTask' warnings appear (only related to CloudKit) with no code of mine running. CoreData: CloudKit: CoreData+CloudKit: -[PFCloudKitExporter analyzeHistoryInStore:withManagedObjectContext:error:](501): <PFCloudKitExporter: 0x600000301450>: Exporting changes since (0): <NSPersistentHistoryToken - { "4B90A437-3D96-4AC9-A27A-E0F633CE5D9D" = 906; }> CoreData: CloudKit: CoreData+CloudKit: -[PFCloudKitExportContext processAnalyzedHistoryInStore:inManagedObjectContext:error:]_block_invoke_3(251): Finished processing analyzed history with 29501 metadata objects to create, 0 deleted rows without metadata. CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _scheduleAutomatedExportWithLabel:activity:completionHandler:](2800): <NSCloudKitMirroringDelegate: 0x6000015515c0> - Beginning automated export - ExportActivity: <CKSchedulerActivity: 0x60000032c500; containerID=<CKContainerID: 0x600002ed3240; containerIdentifier=iCloud.com.nitramluap.Somnus, containerEnvironment="Sandbox">, identifier=com.apple.coredata.cloudkit.activity.export.4B90A437-3D96-4AC9-A27A-E0F633CE5D9D, priority=2, xpcActivityCriteriaOverrides={ Priority=Utility }> CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate executeMirroringRequest:error:](765): <NSCloudKitMirroringDelegate: 0x6000015515c0>: Asked to execute request: <NSCloudKitMirroringExportRequest: 0x600002ed2a30> CBE1852D-7793-46B6-8314-A681D2038B38 2021-08-13 08:41:01.518422+1000 Somnus[11058:671570] [BackgroundTask] Background Task 68 ("CoreData: CloudKit Export"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this. 2021-08-13 08:41:03.519455+1000 Somnus[11058:671570] [BackgroundTask] Background Task 154 ("CoreData: CloudKit Scheduling"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this. Just wondering if anyone else is having a similar issue? It never had a problem syncing an initial database restore prior to iOS 15 (beta 4) and the problems started right after installing iOS 15 (beta 4). I've submitted this to Apple Feedback and am awaiting a response (FB9412346). If this is unfixable I'm in real trouble (and my users are going to be livid). Thanks in advance!
22
0
10k
Aug ’21
[Core Data]: threw while encoding a value. with userInfo of (null)
I am getting the following error while saving data to CoreData. my model has the dictionary property. I created NSSecureCoding and NSSecureUnarchiveFromDataTransformer classes. please check if i can encode my model correctly. I couldn't understand what I am doing wrong ? The problem is not with Dictionary or Data properties. Why can't I save data to CoreData? I know little English. Thank you for your understanding. GitLab Project Link: It is a very simple one page project. I will be glad if you check it out. Core Data Test Project Console Output: 2021-08-21 23:58:18.490834+0300 CoreDataTest[35689:2901360] [error] error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x2827f0240> , <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo of (null) CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x2827f0240> , <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo of (null) Failed to save selected category: A Core Data error occurred. Core Data Entity: My Custom Model: Notice my model has a Dictionary. var sections: [QuestionSections.RawValue : String] I am trying to save dictionary in CoreData. I thought the problem was in the dictionary but the problem is not in the dictionary. class QuestionContainer: NSObject, Codable { var questionCategories: [Question] init(questionCategories: [Question]) { self.questionCategories = questionCategories } } public class Question: NSObject, Codable { var title: String var id: String var questions: [QuestionList] init(title: String, id: String, questions: [QuestionList]) { self.title = title self.id = id self.questions = questions } } public class QuestionList: NSObject, Codable { init(id: String, question: String, isQuestionImage: Bool, isSectionImage: Bool, imageURL: String, imageData: Data? = nil, sections: [QuestionSections.RawValue : String], selected: String, correct: String) { self.id = id self.question = question self.isQuestionImage = isQuestionImage self.isSectionImage = isSectionImage self.imageURL = imageURL self.imageData = imageData self.sections = sections self.selected = selected self.correct = correct } var id: String var question: String var isQuestionImage, isSectionImage: Bool var imageURL: String var imageData: Data? var sections: [QuestionSections.RawValue : String] var selected: String var correct: String } enum QuestionSections: String, Codable { case A = "A" case B = "B" case C = "C" case D = "D" } NSSecure Unarchive From Data Transformer: @objc(QuestionsValueTransformer) class QuestionsValueTransformer: NSSecureUnarchiveFromDataTransformer { static let name = NSValueTransformerName(rawValue: String(describing: QuestionsValueTransformer.self)) override static var allowedTopLevelClasses: [AnyClass] { return [QuestionsNSSecureCoding.self] } public static func register() { let transformer = QuestionsValueTransformer() ValueTransformer.setValueTransformer(transformer, forName: name) } } CoreData Save Function: func saveSelectedQuestion(questionTitle: String, id: String, questions: [QuestionList]) { let questionsCD = QuestionCD(context: persistentContainer.viewContext) questionsCD.title = questionTitle questionsCD.id = id questionsCD.questions = questions do { try persistentContainer.viewContext.save() } catch { print("Failed to save selected category: \(error.localizedDescription)") } }
1
0
1.9k
Aug ’21
How to deduplicate entities with relationships in NSPersistentCloudKitContainer?
In my app I have a defaultJournal: Journal, that automatically gets added on the user's device on launch. There should only be one "default" journal, and I know that deduplication as shown in the Apple Demo, is the correct approach to ensure this on multiple devices. Journal looks something like: class Journal: NSManagedObject { @NSManaged var isDefaultJournal: Bool @NSManaged var entries: Set<JournalEntry>? } Since Journal has a relationship to entries, how can I deduplicate it ensuring that I don't orphan or delete the entries? I am worried that the entries aren't guaranteed to be synced, when we discover a duplicate journal in processPersistentHistory. This would lead to either orphaned or deleted entries depending on the deletion rule. How can one handle deduplicating entities with relationships? For example here is my remove function:     func remove(duplicateDefaultCalendarNotes: [Journal], winner: Journal, on context: NSManagedObjectContext) {         duplicateDefaultCalendarNotes.forEach { journal in             defer { context.delete(journal) } // FIXME: What if all of the journal entries have not been synced yet from the cloud? // Should we fetch directly from CloudKit instead? (could still lead to orphaned/deleted journal that have not yet been uploaded)             guard let entries = journal.entries else { return }             entries.forEach {                 $0.journal = winner             }         }     } A missing tag on a post isn't that bad, but deleting a user's journal is unacceptable. What is the best strategy to handle this?
1
1
882
Oct ’21
CoreData: One or more models in this application are using transformable properties with transformer names that are either unset, or set to NSKeyedUnarchiveFromDataTransformerName.
My app is NOT using CoreData. But I'm seeing this fault error in Console.app from mac when I build my iOS app: CoreData: One or more models in this application are using transformable properties with transformer names that are either unset, or set to NSKeyedUnarchiveFromDataTransformerName. Please switch to using "NSSecureUnarchiveFromData" or a subclass of NSSecureUnarchiveFromDataTransformer instead. At some point, Core Data will default to using "NSSecureUnarchiveFromData" when nil is specified, and transformable properties containing classes that do not support NSSecureCoding will become unreadable. What could be the cause of it? What's the potential security issue it will cause to the app?
1
0
539
Dec ’21
CloudKit: how to handle CKError partialFailure when using NSPersistentCloudKitContainer?
I'm using NSPersistentCloudKitContainer with Core Data and I receive errors because my iCloud space is full. The errors printed are the following: <CKError 0x280df8e40: "Quota Exceeded" (25/2035); server message = "Quota exceeded"; op = 61846C533467A5DF; uuid = 6A144513-033F-42C2-9E27-693548EF2150; Retry after 342.0 seconds>. I want to inform the user about this issue, but I can't find a way to access the details of the error. I'm listening to NSPersistentCloudKitContainer.eventChangedNotification, I receive a error of type .partialFailure. But when I want to access the underlying errors, the partialErrorsByItemID property on the error is nil. How can I access this Quota Exceeded error? import Foundation import CloudKit import Combine import CoreData class SyncMonitor { fileprivate var subscriptions = Set<AnyCancellable>() init() { NotificationCenter.default.publisher(for: NSPersistentCloudKitContainer.eventChangedNotification) .sink { notification in if let cloudEvent = notification.userInfo?[NSPersistentCloudKitContainer.eventNotificationUserInfoKey] as? NSPersistentCloudKitContainer.Event { guard let ckerror = cloudEvent.error as? CKError else { return } print("Error: \(ckerror.localizedDescription)") if ckerror.code == .partialFailure { guard let errors = ckerror.partialErrorsByItemID else { return } for (_, error) in errors { if let currentError = error as? CKError { print(currentError.localizedDescription) } } } } } // end of sink .store(in: &subscriptions) } }
1
1
1.1k
Dec ’21
How to put app-specific logic between migration steps?
There was a section in the talk about how we can break down migration into smaller changes, and that we have an opportunity to run app-specific code in between migration steps. However the talk didn't touch on how can can achieve this, besides a single sentence, which doesn't give enough detail at least for me to figure out how to do it. Intuitively, an event loop could be built that opens the persistent store with the lightweight migration options set and iteratively steps through each unprocessed model in a serial order, and Core Data will migrate the store. Given the automatic nature of the lightweight migrations, especially in the case where we're using NSPersistentCoordinator, doesn't the automatic system just zoom through all of the migrations from model A --> A' --> A'' -> B? How to we make it stop so we can execute our own app code? Thanks!
2
2
1k
Jun ’22
Not receiving Persistent Store Remote Change Notification.
Before the code... CloudKit, background mode (remote notifications) and push notifications are added to Capabilities. Background sync is working fine and view loads current store on manual fetch. Code that initialises the persistent container in app delegate... - (NSPersistentCloudKitContainer *)persistentContainer {     // The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it.     @synchronized (self) {         if (_persistentContainer == nil) {             _persistentContainer = [[NSPersistentCloudKitContainer alloc] initWithName:@"Expenses"];             [_persistentContainer loadPersistentStoresWithCompletionHandler:^(NSPersistentStoreDescription *storeDescription, NSError *error) {                 if (error != nil) {                     __block NSPersistentStoreDescription *sDescription = storeDescription;                     dispatch_async(dispatch_get_main_queue(), ^(){                         [sDescription setOption:[NSNumber numberWithBool:YES] forKey:@"PersistentHistoryTracking"];                         [sDescription setOption:[NSNumber numberWithBool:YES] forKey:@"NSPersistentStoreRemoteChangeNotificationOptionKey"];                     }); #ifdef DEBUG                     NSLog(@"Unresolved error %@, %@", error, error.userInfo); #endif                     abort();                 }                 else #ifdef DEBUG                     NSLog(@"Store successfully initialized"); #endif             }];         }     }     return _persistentContainer; } In Home view controller which is the initial view controller i am adding an observer for the remote notification...     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadViewONCKChangeNotification) name:NSPersistentStoreRemoteChangeNotification object:[appDelegate.persistentContainer persistentStoreCoordinator]]; I am not receiving any store change notifications. Have added breakpoints to see if selector is fired. no go. CloudKit Console also doesn't show any pushes for the concerned time period.
4
0
1.2k
Aug ’22