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
539
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
1.9k
Jan ’17
CoreData error: API Misuse: Attempt to serialize store access on non-owning coordinator (PSC = 0x174262940, store PSC = 0x0)
Hello,I am observing the following error message in the console window of Xcode when running my app (on iOS).CoreData: error: API Misuse: Attempt to serialize store access on non-owning coordinator (PSC = 0x174262940, store PSC = 0x0)I can't seem to pin down the specific operations that are causing it. It almost seems like it is something that Core Data is emitting at some point after whatever the offending operation is. The Core Data setup in the app is done using a UIManagedDocument and in addition I am adding some private queue concurrency contexts where the parent is the managed context in the document (which is the main). Auto save of the UIManagedDocument is turned on. In addition at certain points the app is also doing explicit save of these private contexts. I don't see any ill affects due to the message but I would like to get to the bottom of the issue. I did do searching and there was an old posting where someone fixed it by saving their managed context before using a fetched results controller it was associated with. This seems wrong to me as having to a do a save before using the fetched results controller might catch updates to the managed objects that are in the middle of being made and aren't ready for saving yet because a save could end up violating a relationship constraint.Someone also suggested to make sure the entities were being created with NSEntityDescription.insertNewObject which I double checked that they are.I have -com.apple.CoreData.ConcurrencyDebug set to 1 and when there were other concrrency issues it helped. However with this particular situation it just emits the message and continues. Is there a way to get Core Data to break in the debugger for his message? Any ideas on how I might get to the bottom of this issue or settings I can enabled are greatly appreciated.Thanks Robert
6
0
7.1k
Oct ’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.6k
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.3k
Aug ’19
How to save game data to iCloud?
Hello, I'am an Unity game developer. Iam using custom Binary files to save game progress data (encoded strings, int, bool etc.). Now before I build my project/game to Xcode and upload it to the Appstore, I want the user to be able to save their progress to the iCloud so they can play on multiple devices and restore/override their game data if needed. However I can't find online a step for step guide on how to achieve this. The data that I would need to store for 1 user would probably not be more then 100 int/bool/float etc. I want to know what "Cloud system" I should use in my situation, and how to synchronize my binary files to iCloud. Help would very much be appreciated!
9
0
7.8k
Sep ’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.5k
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
659
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
706
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.2k
Jul ’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.8k
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
849
Oct ’21
CloudKit initial sync and background audio leads to high CPU app termination
I have a music app that can play in the background, using AVQueuePlayer. I'm in the process of adding support for CloudKit sync of the CoreData store, switching from NSPersistentContainer to NSPersistentCloudKitContainer. The initial sync can be fairly large (10,000+ records), depending on how much the user has used the app. The issue I'm seeing is this: ✅ When the app is in the foreground, CloudKit sync uses a lot of CPU, nearly 100% for a long time (this is expected during the initial sync). ✅ If I AM NOT playing music, when I put the app in the background, CloudKit sync eventually stops syncing until I bring the app to the foreground again (this is also expected). ❌ If I AM playing music, when I put the app in the background, CloudKit never stops syncing, which leads the system to terminate the app after a certain amount of time due to high CPU usage. Is there any way to pause the CloudKit sync when the app is in the background or is there any way to mitigate this?
3
0
1.8k
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
511
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