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

How do I prepare CloudKit data for Swift Charts?
I have created a simple app where a user is tracking their mood. A simple click of the button inserts the necessary data to a CloudKit database. So I consider each record as a 'transactional' record. I am able to successfully query the data and present in a list view. I am able to sort and incorporate simple predicates. I am now at a point in my development that I would like to add a pie chart based on the users data and I am not sure how to roll-up the data / group by the data / aggregate the data [I am not sure what the correct terminology is within Swift] The pie chart would show the various moods that the exists in the CloudKit database and the slices would be sized based on the count of each mood. Any guidance that you can provide would be greatly helpful!
1
0
424
Feb ’24
Crash in CoreData (_PFExternalReferenceData)
I'm currently facing an interesting issue. A customer is reporting back that my app is crashing on launch for them. I can see the crash logs (using AppCenter for crash management), and the reason the app is crashing seems to be in CoreData: (Attaching text for seachability, and screenshot for readability): libsystem_platform.dylib _platform_memmove$VARIANT$Haswell CoreData -[_PFExternalReferenceData initForExternalLocation:safeguardLocation:data:protectionLevel:] CoreData -[NSSQLSavePlan _populateRow:fromObject:timestamp:inserted:shouldAddToRowCache:] CoreData -[NSSQLSavePlan _createRowsForSave] CoreData -[NSSQLSaveChangesRequestContext executePrologue] CoreData -[NSSQLCore dispatchRequest:withRetries:] CoreData -[NSSQLCore executeRequest:withContext:error:] CoreData -[NSPersistentStoreCoordinator executeRequest:withContext:error:] CoreData -[NSPersistentStoreCoordinator _routeHeavyweightBlock:] CoreData -[NSPersistentStoreCoordinator executeRequest:withContext:error:] CoreData -[NSManagedObjectContext save:] I have never seen that crash before, it's the first time it is appearing since CoreData has been incorporated into the app (in 2016 or so). Any hints on what could possibly be happening? I am unable to provoke the crash on my end, thus debugging is quite interesting.
1
0
293
Feb ’24
CoreData with cloudkit sync - partially broken.
When I add or delete data of my entity type I can see the updates (between the simulator and the phone) but when i edit I dont see the updates although table view is reloaded. The console says Ignoring remote change notification because it didn't change any entities tracked by persistent history When I rebuild the app for both device and simulator I see it reflecting the most current changes. Any help? Neerav
0
0
283
Feb ’24
iCloud Sync Not Working on Physical Device
I have iCloud sync working in the simulator, where I signed in with my Apple ID on two simulators and it syncs fine. But when I upload the same build to TestFlight and install it on two of my physical devices, it does not sync. Each device behaves as if they only have a local store, eg. each can save and load fine locally. I already tried pushing my schema to production, but it still does not work, even when given 24 hours to see if it would sync. I have also tried restarting both devices and deleting and re-installing the app on both devices. I have also confirmed that iCloud is turned on in the settings app for my app. I saw this post on Stackoverflow, which seems to be related to my issue, but the suggestions there did not work either. I also saw this post: https://www.hackingwithswift.com/forums/swiftui/swiftui-app-failing-to-sync-cloudkit-data-but-only-in-testflight-version/10714 However I did not understand the accepted answer, and none of the other suggestions worked either.
0
0
530
Feb ’24
Aggregated Data Table (Reporting Table) in CloudKit database
I need to track user actions, for example video view count. Then the data is used to get most popular videos for last 7 days, 30 days and for a year. For this purpose I have created a Downloads table with timestamp and video fields. Each time user opens the catalog, I'm running queries to get Downloads and sort the videos based on them. This is a working, but not the efficient solution. A good option is to add aggregated data table storing summary counts for the popular queries - countFor7Days, etc. This will improve query performance. But it requires a job that would update the aggregate table every day. The question is how to implement this job in CloudKit? Is there are such built-in feature, or I need a custom service running somewhere?
3
1
459
Feb ’24
App unresponsive when calling record(for:) on NSPersistentCloudKitContainer
I'm experiencing an unresponsive UI since MacOS 14.0 and iOS 17.0 when calling record(for: ) or recordID(for:) on the instance of NSPersistentCloudKitContainer. On MacOS, the UI freeze almost always happens when calling the function. On iOS, it is necessary that the device (or simulator) does not have any network connection. I would like to ask if anyone experienced the same problem. I have posted the problem twice to Apple via the Feedback app (once for iOS and once for MacOS). No reply yet on MacOS but on iOS Apple marked it as resolved because apparently no one but me has experienced this problem. In the meantime, I have set up a minimum reproducible example app (MRE).: https://github.com/DominikButz/NotesApp-Cloud-Kit-Record-UI-Freeze- Anyone interested, please read the readme of the repository. It includes step by step instructions on how to reproduce the bug. I can't rule out I have misunderstood the usage of CoreData and CloudKit - in that case please point me in the right direction. The app I'm working on should also work offline (and on MacOS!) but it doesn't do so properly as long as this bug exists. I'm exploring switching to SwiftData (which would mean no one using macOS 13 / iOS 16 can use my app...) but I would still need to access cloud kit records even with SwiftData and I fear the bug also exists in SwiftData. Thanks
3
0
352
Feb ’24
coredata entities from public configuration are not synchronized to cloudkit
In Core data public configuration, added new attribute to entities, new entities, but the changes are neither synchronized nor data is transferred to existing container schema in cloudkit. private var _publicPersistentStore: NSPersistentStore? var publicPersistentStore: NSPersistentStore { return _publicPersistentStore! } private var _privatePersistentStore: NSPersistentStore? var privatePersistentStore: NSPersistentStore { return _privatePersistentStore! } private var _sharedPersistentStore: NSPersistentStore? var sharedPersistentStore: NSPersistentStore { return _sharedPersistentStore! } static let shared = PersistenceController() static var preview: PersistenceController = { let result = PersistenceController(inMemory: true) let viewContext = result.container.viewContext do { try viewContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nsError = error as NSError fatalError("Unresolved error \(nsError), \(nsError.userInfo)") } return result }() let container: NSPersistentCloudKitContainer init(inMemory: Bool = false) { container = NSPersistentCloudKitContainer(name: “GS”) if inMemory { container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null") } guard let defaultDescription = container.persistentStoreDescriptions.first else { fatalError("###\(#function): failed to retrieve a persistent store description.") } let containerIdentifier = defaultDescription.cloudKitContainerOptions!.containerIdentifier print(containerIdentifier) print(defaultDescription.url as Any) let url = defaultDescription.url?.deletingLastPathComponent() print(url as Any) // Public let publicDescription = NSPersistentStoreDescription(url: url!.appendingPathComponent("public.sqlite")) publicDescription.configuration = "Public" print(publicDescription.url) let publicOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: containerIdentifier) publicOptions.databaseScope = .public publicDescription.cloudKitContainerOptions = publicOptions publicDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) publicDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) // Private let privateDescription = NSPersistentStoreDescription(url: url!.appendingPathComponent("private.sqlite")) privateDescription.configuration = "Private" print(privateDescription.url) let privateOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: containerIdentifier) privateOptions.databaseScope = .private privateDescription.cloudKitContainerOptions = privateOptions privateDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) privateDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) // Shared guard let sharedDescription = privateDescription.copy() as? NSPersistentStoreDescription else { fatalError("#\(#function): Copying the private store description returned an unexpected value.") } sharedDescription.url = url!.appendingPathComponent("shared.sqlite") print(sharedDescription.url) sharedDescription.configuration = "Shared" let sharedOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: containerIdentifier) sharedOptions.databaseScope = .shared sharedDescription.cloudKitContainerOptions = sharedOptions sharedDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) sharedDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) container.persistentStoreDescriptions = [publicDescription, privateDescription, sharedDescription] container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } else { if let cloudKitContainerOptions = storeDescription.cloudKitContainerOptions { if #available(iOS 16.0, *) { if .public == storeDescription.cloudKitContainerOptions?.databaseScope { print("loaded public store") // self._publicPersistentStore = container.persistentStoreCoordinator.persistentStore(for: storeDescription.url!) } else if .private == storeDescription.cloudKitContainerOptions?.databaseScope { print("loaded private store") //self._privatePersistentStore = container.persistentStoreCoordinator.persistentStore(for: storeDescription.url!) } else if .shared == storeDescription.cloudKitContainerOptions?.databaseScope { print("loaded shared store") //self._sharedPersistentStore = container.persistentStoreCoordinator.persistentStore(for: storeDescription.url!) } } else { // Fallback on earlier versions } } } }) container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergeByPropertyStoreTrumpMergePolicy // external changes trumping in-memory changes. } func save() { let context = container.viewContext if context.hasChanges { do { try context.save() } catch { // Show some error here print("save error") } } } } Tried new container on cloudkit, problem persists. Working previously until I updated Xcode to 15.2 and iOs 16.2. Can you please tell me why coredata is not synchronized for public configuration.
2
0
348
Feb ’24
app name in iCloud "Manage Storage" list is wrong
Hello: We have a problem and we don't know how to solve it. We have developed the following two App: app1 and app2 Both App have the function of using iCloud.The iCloud container id of app1 and app2 is the same.We use the document storage function of iCloud. We originally planned to share iCloud data in two app, so we used the same iCloud container, and we released app1 and then app2. Due to the slow progress of app2 development, the related functions of iCloud have not been added to the code yet. But we found a problem. In the storage management of "setup", iCloud, the display name of app1 is app2's name, not app1's name. This causes many of our users to delete the iCloud data of the application by mistake, resulting in losses. Now our question is: What caused the name in app1's iCloud storage management list to be displayed as the name of app2? How should it be solved?
1
0
411
Feb ’24
NSPersistentCloudkItContainer and iCloud synchronization speed issues
In our app, there is a scenario where we write and delete approximately 100MB of files to the iCloud server at once using NSPersistentCloudkItContainer(CoreData). While write, read, and delete operations are immediately reflected in the local database, there is a noticeable delay when accessing the CloudKit Database dashboard. Here is the testing approach we have tried: Data Insert Test
 Prepare around 100MB of data.
 Write the data to CoreData on device A.
 When launching the app on device B, it takes about 5 minutes for the data to be fully synchronized. Data Deletion Test Remove all the added data on device A (immediately reflected in local storage.)
 After performing step 1, leaving device A idle takes about 3 minutes for the deletion to be reflected on device B.
 if the app is deleted on device A after step 1, deletion information does not reach device B. Upon reinstalling the app on device A, the deleted data reappears on device B (synchronized data). The ongoing occurrence of these issues has raised several questions regarding cloud synchronization and synchronization speed: Is the synchronization speed of the Testflight app the same as the one received from the AppStore? Are there traffic limitations per account or device? Despite different perceived speeds for each account or device, is there any factor influencing synchronization speed other than network conditions?
2
0
361
Jan ’24
How to get notified on CKError.quotaExceeded
Hi all, I have an iOS app which uses CloudKit and the standard NSPersistentCloudKitContainer, which I rely on for syncing app data between the user's devices. If the user's iCloud account is full I can see a log message while debugging in Xcode shortly after startup which looks something like this: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2183): <NSCloudKitMirroringDelegate: 0x281ddc1e0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringExportRequest: 0x2841e00f0> 51383346-87BA-44D8-B527-A0B1EE35A0EF' due to error: <CKError 0x282c50db0: "Partial Failure" (2/1011); "Failed to modify some records"; uuid = 7BA17495-4F05-4AF4-A463-C0DF5A823B2E; container ID = "iCloud.com.neufsters.pangram"; partial errors: { E30B2972-FD4B-4D2A-BD1C-EB6F33F5367D:(com.apple.coredata.cloudkit.zone:__defaultOwner__) = <CKError 0x282c155f0: "Quota Exceeded" (25/2035); server message = "Quota exceeded"; op = FC4D3188D0A46ABC; uuid = 7BA17495-4F05-4AF4-A463-C0DF5A823B2E; Retry after 315.0 seconds> 2FC9A487-D630-444D-B7F4-27A0F3A6B46E:(com.apple.coredata.cloudkit.zone:__defaultOwner__) = <CKError 0x282c52820: "Quota Exceeded" (25/2035); server message = "Quota exceeded"; op = FC4D3188D0A46ABC; uuid = 7BA17495-4F05-4AF4-A463-C0DF5A823B2E; Retry after 315.0 seconds> 903DD6A0-0BD8-46C0-84FB-E89797514D9F:(com.apple.coredata.cloudkit.zone:__defaultOwner__) = <CKError 0x282c513e0: "Quota Exceeded" (25/2035); server message = "Quota exceeded"; op = FC4D3188D0A46ABC; uuid = 7BA17495-4F05-4AF4-A463-C0DF5A823B2E; Retry after 315.0 seconds> }> I would like to know how I can get a callback of some sort so I can run code if this CloudKit/CoreData error happens. In particular I'd like to put up some sort of warning to the user letting them know their data isn't going to sync. Please note that I'm not looking for how to do error handling as a result of a user-initiated CloudKit API call. I'm looking for how to get notified when the background syncing logs errors like the above. Thanks, Russ
4
1
457
1w
SwiftData + CloudKit process for deduplication / consuming relevant store changes?
It is often the case that offline devices can add duplicate entities that needs to be merged when CloudKit syncs. Consider user-created tags. A user might create a Note, and then tag it with a newly created tag “Family.” On a separate offline device, they might create another note, and create another tag also called ”Family.” On device sync, both duplicate ”Family” tags would need to be identified as duplicates based on their name property, merged to a single entity, and their original relationships consolidated to the single merged Tag. And this needs to happen before the CloudKit sync data is presented to the UI in the main context. With Core Data we have the mechanism to consume relevant store changes described here. These tools allow us to listen for remote change, then process them appropriately (e.g. remove / merge duplicates) and then merge the changes into the app’s main context. This perfectly solves the problem described in the first paragraph above. Apple provides code using this mechanism for deduplicating tags in a sample app. Is there a mechanism to solve this deduplication problem using SwiftData technology without implementing and maintaining a parallel Core Data stack?
2
2
710
Feb ’24
CoreData+CloudKit w/ Large Public Database
What is the recommended architecture for a CoreData+CloudKit iOS App that has a large public database? Assume the public database contains 10,000+ Locations from which a User would select a few as favorites. Totally impractical to mirror the locations such that they appear in the App's CoreData having been synced from the .public CloudKit database. Presumably one uses the CloudKit API to query the .public database and display some subset of locations for the User to select? (The selected locations can then be stored in the Users .private (or perhaps .shared) database.) How does one configure CoreData + CloudKit for this scenario? Is there another approach?
2
0
466
Jan ’24
CloudKit push notification not working on Sonoma
I have an app that uses CloudKit push notification (CKDatabaseSubscription) and it's been working all along on Ventura 13.5/Xcode 15.0. But since I upgraded my Mac to Sonoma 14.3/Xcode 15.2, my app no longer receives push notification (didReceiveRemoteNotification is not called) on the Mac. Is this a known issue of either Sonoma or Xcode 15.2? FYI, the same code works perfectly on iOS 17.2.
0
0
318
Jan ’24
CloudKitDaemon [804] Indentity Error
Hello, I build my app on Unity 2021 using the service Unity Cloud Build. I enabled iCloud key-value storage and it correctly show up in the entitlement file. Whenever I try to make a cloud save, Unity Logs says that the process was successful but it didn't save anything on the cloud. I had a look to the logs on my device and I found this strange error: cloudd(CloudKitDaemon)[804] <Error>: Identity set <private> was expected to have a current key set <private>. Error Domain=securityd Code=-25300 UserInfo={NSLocalizedDescription=<private>} cloudd(CloudKitDaemon)[804] <Error>: Identity set <private> does not have a current key set. Not using it. cloudd(CloudKitDaemon)[804] <Error>: Didn't get a service identity from the PCS framework I searched online but I couldn't find anything informative. Any suggestions?
3
0
571
Jan ’24
Using CloudKit JS for a React web app
Hello, everyone! I'm currently working in creating a new web app that will replicate the functionalities of an existing iOS and Mac app. However, since those apps rely on CloudKit to manage all user information, we decided on using CloudKit JS as our backend for our web app. The framework we chose for developing our frontend is React. The question is, since this documentation only mentions the CloudKit JS usage through a CDN (embedded directly in the HTML file) I wanted to ask: is there a "suggested" method for using CloudKit JS in a React project other than importing the CDN in the main html file? in case not, should we use a "traditional" server to access data like they suggest in this thread? All your help will be very much appreciated. Best regards, Eduardo
0
1
534
Jan ’24
How to sync data between iOS and OSX apps with CloudKit?
We have an iOS App developed in SwiftUI that saves data to CloudKit using NSPersistentCloudKitContainer. If I modify any of this data, the changes are synchronized on other iOS devices without problem. We also have an OSX App with StoryBoard using NSPersistentCloudKitContainer to share the same data with iOS devices. Changes made on OSX are updated immediately on iOS devices. But if any data is modified in iOS, it is not updated in the OSX application. Simply by doing Command-Tab twice the OSX app displays the new data. It appears that CloudKit Push Notifications are not causing the OSX application to detect that there are changes to the data and that it needs to be updated. In both cases an NSFetchedResultsController is created and a delegate is placed. The iOS one is called but the OSX one is not. The only difference in the code is that in the iOS app with SwiftUI it is done: var body: some Scene { WindowGroup { InitialTab() .environment(\.managedObjectContext, DataManager.shared.viewContext) } } but this is not done in OSK since NSView does not have the .environmet method. Could this be the problem? What should I do to update data without switching applications on OSX? Any help would be appreciated, Thank you so much.
0
0
236
Jan ’24
CloudKit Sync Complete Event/Notification
How does one know when the CloudKit data in a CoreData+CloudKit (NSPersistentCloudKitContainer) has been fully synchronized. UseCase would be a user starts the App on a second device, user deletes then reinstalls the App, another User accepts a share and the share needs to sync. Is the containerEventChanged Notification for 'import success' the definitive event? CoreData: CloudKit: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _finishedRequest:withResult:](3403): Finished request: <NSCloudKitMirroringImportRequest: 0x600002345d10> 729A742A-7F3B-42F1-B04C-72705D41FFEF with result: <NSCloudKitMirroringResult: 0x600000c4edc0> storeIdentifier: 79FA5848-A135-41B1-A36A-09F2F914D23D success: 1 madeChanges: 0 error: (null) As the sync could be time-consuming, is there a way to identify a single CloudKit record?
1
0
686
Jan ’24
'Establishing a User' - CloudKit Discoverability Deprecated.
My App uses Core Data + CloudKit and requires use of CloudKit to store persistent data, that will be shared between Users. I’d like to establish the User’s identity - like so they can augment their Core Data ‘Player’ entity w/ App specific info. Certain interfaces have been deprecated (‘user discoverability’). I’ve taken to creating a ‘dummy shared zone’ and extracting the ‘owner.userIdentity': public func establishUser () async -> User? { let container = cloudKitContainer // If we store the userUUID then the implication is that the `user` can // never be deleted; that is fair enough. let userUUIDKey = "userUUID" var userIdentity = Optional<CKUserIdentity>.none do { // // We'll store the UUID of the CoreData `User` in the CloudKit `User` record. If there // is no UUID in CloudKit, then this will be the first time the User has ever started // the App. We'll create a user and update the CloudKit `User` record // let userID = try await container.userRecordID () let userRecord = try await container.publicCloudDatabase.record (for: userID) // If the `userRecord` does not have a `userUUIDKey` then we must create a new `User`. if nil == userRecord[userUUIDKey] { // See if the user has the required iCloud account. let userStatus = try await container.accountStatus() guard userStatus == .available else { print ("JKP: \(#function) accountStatus: \(userStatus)") return nil } // // Create a `dummyShare` (in a 'dummyZone') so we can access the share's owner // That owner will have our `userIdentity` // do { let dummyZone = CKRecordZone (zoneName: UUID().uuidString) let dummyShare = CKShare (recordZoneID: dummyZone.zoneID) print ("JKP: User: Establish Zone: \(dummyZone.zoneID.zoneName)") // Save the dummyZone and then the dummyShare (for/in the dummyZone) let _ = try await container.privateCloudDatabase.save (dummyZone) let _ = try await container.privateCloudDatabase.save (dummyShare) // Extract the dummyShare's owner's identity - which is 'us/me' userIdentity = dummyShare.owner.userIdentity // Cleanup by deleting the 'dummyShare' and then the 'dummyZone' let _ = try await container.privateCloudDatabase.deleteRecord (withID: dummyShare.recordID) let _ = try await container.privateCloudDatabase.deleteRecordZone (withID: dummyZone.zoneID) } catch { print ("JKP: User Establish Error: \(error.localizedDescription)") } // Create `newUser` with the `userRecordId`. We'll use this to lookup the // Core Data User when players appear in a League. let newUser = User.create (context, scope: Player.Scope.owner, name: (userIdentity?.nameComponents ?? PersistenceController.nameDefault), identification: userIdentity?.lookupInfo .map { PlayerIdentification.create (lookupInfo: $0) } ?? PlayerIdentification()) … } Is this how getting the userIdentity is meant to be done (w/o using the deprecated interfaces)? The deprecated interfaces, when warned in Xcode, reference a sample project; that project doesn’t actually use/get the userIdentity. Also the deleteRecord and deleteRecordZone don’t appear to remove the dummy zone in CloudKit; why?
1
0
381
Jan ’24