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 + SwiftData
I am currently working on an app that utilizes SwiftData, and I am planning to integrate CloudKit. My current challenge involves managing a Day object that gets inserted when the date changes to track daily progress. Additionally, I want to prompt users to create a username during the app's onboarding process. I am concerned that this could lead to synchronization issues, such as duplicate entries for the same day or multiple user accounts being created. I assume blocking the app until everything is synced from CloudKit is not a practical solution. Does anyone have any recommendations on how to handle this? Furthermore, I would like to implement a community feature where users can post content. I noticed that CloudKit offers a public database. Is this database suitable for such a feature, or would I need to develop a separate backend to support it?
0
0
81
1d
Do remote notifications work on macOS when app is closed?
I have a native SwiftUI Mac app which is based off my iOS app and includes Core Data with iCloud sync. As per my understanding, when a user makes a change on one of the devices a remote notification is sent to the others. I have a widget which displays information from Core Data and the remote notification makes the widget update its information on the next timeline refresh without the user having to open the app manually. My question is, if an app is closed on macOS so it's not even running in the Dock, do remote notifications work? This page says "the delegate receives this message when the application is running and a remote notification arrives for it". Does that mean the app won't receive remote CloudKit notifications when closed on macOS?
1
0
78
2d
SwiftData doesn't parse my object correctly
Hello, im trying to parse a JSON Request into a Swift Data Model. The specific bug happens with the nutriscore. It works perfectly fine if I do my request and Decode or Encode the Model directly. But when im trying to add it to the Database the field is empty. Somehow when im iterating through each product (my model) and console log it, it works. But only if there is one product in my database. sometimes when im adding another product, it somehow deletes(?) all nutriscores and the console log prints "nil" for all products. even for the product it worked before. This right here is the way I insert into my database which should be perfectly fine. And the printing works also perfectly fine and it always displays the correct nutriscore func dataScanner(_ dataScanner: DataScannerViewController, didAdd addedItems: [RecognizedItem], allItems: [RecognizedItem]) { for item in addedItems { if case let .barcode(barcode) = item { performAPIRequest(with: barcode.payloadStringValue!) { result in switch result { case .success(let product): ... var descriptor: FetchDescriptor<Product> { var descriptor = FetchDescriptor<Product>( predicate: #Predicate { $0.code == product.code } ) descriptor.fetchLimit = 1 return descriptor } var products: [Product] = [] products = try! self.parent.context.fetch(descriptor) print(product.nutriscore ?? "no nutri"); //WORKS PERFECTLY FINE!! if let existingProduct = products.first { existingProduct.amount! += 1 existingProduct.lastScannedAt = Date() } else { self.parent.context.insert(product) } self.processMeals() case .failure(let error): print("Error: \(error)") } } } } } This has to be a SwiftData Bug, or why doesn't it work
1
0
101
3d
Is there a way to search in SwitData optional to many relationships?
Done this model: @Model public final class Category: Codable { var nom: String = "" @Relationship(deleteRule: .cascade, inverse: \Property.category) var properties: [Property]? } How to create #predicate to search text in like… let predicate = #Predicate<Category> { category in searchText.isEmpty || category.nom.localizedStandardContains(searchText) || category.properties.contains { $0.nom.localizedStandardContains(searchText) } } without this error: SQLCore dispatchRequest: exception handling request: <NSSQLCountRequestContext: 0x6000038dc620>, to-many key not allowed here with userInfo of (null)
0
0
112
6d
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
140
1w
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
180
1w
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
142
1w
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
126
2w
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
106
2w
Restart sync when using NSPersistentCloudKitContainer
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)?
0
0
149
2w
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
165
2w
Can SwiftData @Model with .externalStorage be used with CloudKit?
Hi, I'm about to adopt .externalStorage but I will also use CloudKit in the near future. I did not find any reference that list of requirements for SwiftData models to be used with CloudKit, only for Core Data models. It seems those Core Data requirements (like no-unique) apply to SwiftData as well. However I did not find any info on this: Can @Attribute(.externalStorage) be used when I want to sync my model with CloudKit?
2
0
141
5d
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
155
2w
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
199
2w
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
0
229
2w
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
157
3w
How to store Public Data in ICloud
I have been working on an ios application which I decided to use the new SwiftData architecture, and I now have realized that SwiftData does not support public or shared databases using SwiftData. I am a new and upcoming Swift developer, who has been self learning the Apple Swift technology. I just learned in this forum that Swift Data does not support Public and Shared Data and I also understand that no plans that have been announced to addressed this feature in the IOS 18 release time frame. The use case for my application is to implement a social type application, something like applications including X, facebook, etc. These type of applications appear to use Public, Shared and Private data in various existing Apple application. I would like to complete an application using Swift using ICloud, but I must assume that these current social applications are using other technologies. I am assuming you can do this in Core Data, but my understanding is Apple is asking that we use Swift Data to replace core data. I also am assuming that Swift data is built on core data technology layers. So ... to me it seems hopeful, somehow, to accomplish this using IOS 17 and follow the recommend Swift Data Path. What are my options for completing these data objectives in IOS? I hope I am addressing these questions in the proper and best forum? Much thanks for any suggestions.
2
0
194
3w