CloudKit

RSS for tag

Store structured app and user data in iCloud containers that can be shared by all users of your app using CloudKit.

Posts under CloudKit tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

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
236
May ’24
CloudKit data is lost when reinstalling the app
We worked with SwiftData, and once CloudKit was integrated, the synchronization worked well. Even if I rerun the app, it works just as well. However, when I delete the app and reinstall it, I get a Token Expired error and CloudKit doesn't work properly. My code is organized like this public lazy var modelContext: ModelContext = { ModelContext(modelContainer) }() private lazy var modelContainer: ModelContainer = { let schema = Schema([ Entity1.self, Entity2.self, Entity3.self, ]) let modelConfiguration = ModelConfiguration( schema: schema, groupContainer: .identifier("myGroupContainer"), cloudKitDatabase: .automatic ) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() The error content is as follows error: CoreData+CloudKit: -[PFCloudKitImportRecordsWorkItem fetchOperationFinishedWithError:completion:]_block_invoke(707): <PFCloudKitImporterZoneChangedWorkItem: 0x3022c0000 - <NSCloudKitMirroringImportRequest: 0x3036e7ac0> 1A7E53D4-E95B-423F-8887-66360F6D8865> { ( "<CKRecordZoneID: 0x301bb1bf0; zoneName=com.apple.coredata.cloudkit.zone, ownerName=__defaultOwner__>" ) } - Fetch finished with error: <CKError 0x301bb5650: "Partial Failure" (2/1011); "Couldn't fetch some items when fetching changes"; uuid = 3F346302-C3EE-4F72-820C-988287C92C0A; container ID = "MyContainerID"; partial errors: { com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x301bb1830: "Change Token Expired" (21/2026); server message = "client knowledge differs from server knowledge"; op = 515034AC3ADC4348; uuid = 3F346302-C3EE-4F72-820C-988287C92C0A> }> error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _importFinishedWithResult:importer:](1390): <PFCloudKitImporter: 0x3000a1240>: Import failed with error: <CKError 0x301bb5650: "Partial Failure" (2/1011); "Couldn't fetch some items when fetching changes"; uuid = 3F346302-C3EE-4F72-820C-988287C92C0A; container ID = "MyContainerID"; partial errors: { com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x301bb1830: "Change Token Expired" (21/2026); server message = "client knowledge differs from server knowledge"; op = 515034AC3ADC4348; uuid = 3F346302-C3EE-4F72-820C-988287C92C0A> }> Forcing the ModelContainer to be reinitialized fixes the problem, it's a problem to get this error in the first place, the error doesn't even go to fatal for me, so I don't even know how to verify that it's happening. Is there something I'm doing wrong, or do you have any good ideas for solving the same problem?
2
0
323
May ’24
CloudKit database - 500 Internal error
As of yesterday all queries my app makes to the CloudKit database, and requests via the CloudKit console result in 500 internal errors. We have made no changes to the database or app that could have caused this. The status page for CloudKit database is green. Here is a response from the CloudKit console: {code: 500, message: "internal-error", reason: "Internal error", detailedMessage: undefined, requestUuid: "808955a2-e564-459e-ba9b-1101917ce1a4"}
1
0
234
May ’24
HealthKit SwiftData sync
Hello, I want to build an app that will allow the user to entry some health related records and be synced with the HealthKit. Any record that is in the HealthKit is stored locally on the device. I find it conceptually unsure if I should be storing the HealthKit records in the SwiftData to make the user records available across the iCloud synced devices. Should I read the HealthKit record, make a copy of it (including it's ID) on my app's data in SwiftData? How the syncing should be done the right way? thanks.
1
0
469
May ’24
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
196
May ’24
iCloud cannot be accessed by third party App for some users
My App uses Core Data with Cloudkit when users purchased subscription (and uses only Core Data without subscription). My App should normally appear under 'Settings > [User Name] > iCloud > Apps using iCloud - Show All'; however, some users feedback that they my App cannot access iCloud (a message I displayed in my App when CKContainer.default().accountStatus is NOT available or FileManager.default.ubiquityIdentityToken == nil); and they do not see my App name under 'iCloud > Apps using iCloud - Show All'. From the screenshot that one user provided, only Apps from Apple are displayed under 'Apps using iCloud' and no third-party Apps are shown. Since the user can access to 'iCloud > Apple using iCloud', they have signed in to iCloud successfully. They have also tried to restart my App and restart the phone but the iCloud accessibility issue still remains. How is it possible that iCloud is accessible only to Apps from Apple but not to third party Apps? What can developer do to resolve iCloud accessibility issue here?
0
0
163
May ’24
SwiftData+Cloudkit Migration Failed
I have v3 models in coredata (model: Event, Lecture), and make new model in v4 with swiftdata but model name, property is different (model: EventModel, LectureModel). For migration, I add V3Schema, V4Schema and MigrationPlan. enum V4Schema: VersionedSchema { static var models: [any PersistentModel.Type] = [LectureModel.self, EventModel.self ] static var versionIdentifier = Schema.Version(4, 0, 0) } enum V3Schema: VersionedSchema { static var models: [any PersistentModel.Type] = [Event.self, Lecture.self] static var versionIdentifier = Schema.Version(3, 5, 2) } enum ModelMigrationPlan: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] = [V3Schema.self, V4Schema.self] static var stages: [MigrationStage] = [migrateV3ToV4] } extension ModelMigrationPlan { static let migrateV3ToV4 = MigrationStage.custom(fromVersion: V3Schema.self, toVersion: V4Schema.self, willMigrate: willMigrate, didMigrate: { _ in Log.debug(message: "Migration Complete") }) } private func willMigrate(context: ModelContext) throws { try migrateLectures(context: context) try migrateEvents(context: context) try context.save() } private func migrateEventTypes(context: ModelContext) throws { // create new v4 event model using v3 event model. } private func migrateLectures(context: ModelContext) throws { // create new v4 lecture model using v3 lecture model. } static let release: ModelContainer = { let v4Schema = Schema(V4Schema.models) let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "app group id") let databaseURL = containerURL?.appending(path: "**.sqlite") let configuration = ModelConfiguration("**", schema: v4Schema, url: databaseURL!, cloudKitDatabase: .private("**")) #if DEBUG do { try autoreleasepool { let desc = NSPersistentStoreDescription(url: configuration.url) let opts = NSPersistentCloudKitContainerOptions(containerIdentifier: configuration.cloudKitContainerIdentifier!) desc.cloudKitContainerOptions = opts desc.shouldAddStoreAsynchronously = false if let model = NSManagedObjectModel.makeManagedObjectModel(for: V4Schema.models) { let container = NSPersistentCloudKitContainer(name: "**", managedObjectModel: model) container.persistentStoreDescriptions = [desc] container.loadPersistentStores(completionHandler: { _, err in if let err { Log.error(message: "Store open failed: \(err.localizedDescription)") } }) try container.initializeCloudKitSchema() Log.debug(message: "Initialize Cloudkit Schema") if let store = container.persistentStoreCoordinator.persistentStores.first { try container.persistentStoreCoordinator.remove(store) } } } } catch { Log.error(message: "Failed: \(error.localizedDescription)") } #endif return try! ModelContainer(for: v4Schema, migrationPlan: ModelMigrationPlan.self, configurations: configuration) }() But when I run, I got error message. CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _scheduleAutomatedExportWithLabel:activity:completionHandler:]_block_invoke(3508): <NSCloudKitMirroringDelegate: 0x1036b1540> - Finished automatic export - ExportActivity - with result: <NSCloudKitMirroringResult: 0x1035da810> storeIdentifier: ***** success: 0 madeChanges: 0 error: Error Domain=NSCocoaErrorDomain Code=134407 "Request '*****' was cancelled because the store was removed from the coordinator." UserInfo={NSLocalizedFailureReason=Request '****' was cancelled because the store was removed from the coordinator.} I don't know why store was removed from the coordinator. Any have solutions?
2
0
485
May ’24
CloudKit + CloudSave for Unity not building in Xcode
I'm trying to integrate the option to the player to save their data in the cloud, I integrate the CloudKit, change some stuff to make it work and build in Xcode to my phone. But when I try to integrate the CloudSave, 50 unnasigned symbols jump,like this one: Undefined symbol: _CKContainer_Default I managed to fix them by updating the recommended settings for Xcode. But then 4 more errors appear: Sandbox: il2cpp(12538) deny(1) file-read-data /Users/Username/Test Apple Kit 2022/Build/Il2CppOutputProject/IL2CPP/build/deploy_arm64/il2cpp So, don't let me build and I've looked everywhere but no one seems to had this same error
1
0
262
May ’24
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
1
360
May ’24
Deleting CloudKit containers
When I go to Settings and tap on the account, choose iCloud>manage account storage and try to delete the storage associated with an app id developer mode, it doesn't give me the option to delete the data. I have tried using the CloudKit Console to delete the container data, but the entry for the app is still there. How do I delete it?
1
0
266
May ’24
CloudKit User Discoverability
Hello, Prior to iOS 17, it was possible to request user discoverability by calling ‚requestApplicationPermission‘. But now it is deprecated. How is the intended way to do this now? How this is for example handled in the Music App? I think this should be a similar approach. Currently the only option for me seems to save the Email-Address (and maybe phone number) in the CloudKit public database, that other user can discover by this. But that the problem exists, that we need to fetch for changes at phone numbers and mail addresses that are linked to the iCloud account (because user might change anything). Is there a more elegant solution, than just checking the current email addresses and phone numbers at each start of the application (if that is even possible)? For example the Music App has that Switch "Find my by Apple-ID" but I don't know how this is handled in the background. Thanks!
1
0
229
May ’24
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
361
May ’24
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
242
May ’24
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
596
May ’24
CloudKit Private Database Record Zone Limit
I am following this document from Apple to implement sharing with CloudKit. In it, Apple says NSPersistentCloudKitContainer uses CloudKit zone sharing to share objects. Each share has its own record zone on the CloudKit server. CloudKit has a limit on how many record zones a database can have. What is the record zone limit for a private CloudKit database? I can find information about record and participant limits but not on record zone limits.
1
0
143
May ’24
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
273
May ’24
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.4k
May ’24