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

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
Error loading container details.
#1 As a new starter, I just created a new sample app in Xcode and added iCloud capability. On the CloudKit dashboard I do see the container but selecting the specific container shows the following message in red "Error loading container details." #2 I was able to create a new RecortType via the cloud kit dashboard UI but when I try to create a record form the dashboard UI somehow it does not let me select the record type of the record (I see it in the list but its grayed out). I am not sure what the reason for #1 and #2 and if the two issues are related. Could not find any help online. I am trying to create an app directly with cloudKit and Javascript (not a companion IOS app). Any help would
1
2
1.9k
Aug ’23
Please Create a Sendable Version of CKRecord or Make CKRecord Sendable
CKRecord is a class which does not conform to the Sendable protocol. Its fields consist of NSStrings, NSData and others which are not Sendable. I understand that Apple is incrementally modifying objects to be sendable, but I am experiencing and I would assume others are experiencing a very large number of warnings (for now) about CKRecords and Sendable. It may be too much to make CKRecord Sendable and it may be too much to create a Sendable version of CKRecord, but it would be nice if it could at least be investigated. My particular situation is I have created a Protocol named CKMethods which some of my view controllers use to download and upload CKRecords. I suddenly have a large number of warnings about non-sendable types being sent from main actor-isolated context to non-isolated instance method. The CKRecords sent to and from the protocol do not get mutated and I have never had a problem with data races in the years that I have had this protocol. At some point, the warnings will probably become errors and I definitely do not want to get to that point. I am still coming up to speed on Swift Concurrency, so there may be a more simple solution than the one I am working on - creating a Sendable Struct for every CKRecord type that I have in my app and modifying all of the methods to pass the Struct instead of a CKRecord and convert the Struct to a CKRecord for upload and convert the CKRecord to the Struct for download.
3
1
1k
2w
Scrolling in Xcode crash
I have some code from a youtube video that I have completed before, but now when I scroll up, xCode crashes. I have a class with an enum. Sticky headers are there, then as i scroll down, the headers disappear. Then as a // MARK: comes up, we crash. I tried changing the MARK so that it was not bolded, but it still crashes. Is there a setting to disable sticky headers? This was happening in xCode 14.2, and i upgraded, to 14.3, and it went away for a while, but now the problem is back, well intermittently. I did a Clean Build Folder and a Clear All Issues. Still annoying.
3
0
708
Jul ’23
Update Watch Complication with CloudKit
I have an iPhone app the uses CloudKit for Core Data syncing. I also have a companion Apple Watch app that syncs to the same CloudKit records. The watch can be used without the iPhone app as well but they both independently sync to the same CloudKit database. This works reasonably well. As soon as either app is opened, the CloudKit will pull down the latest records. I'd like to add a watch complication that shows the state of the CloudKit records. I supported this by adding a Widget extension, embedded in my watch app. The Core Data database in the watch app is part of an app group, so the complication is able to query the same database. So far so good. I'm running into problems with the complication updating after remote records are changed from the iPhone. Here is what is happening: When records are changed on the iPhone, the data syncs to CloudKit but the watch app is not updated when in the background. This is noticed when you open the app and it takes a second for the view to show the new records. Since Core Data database on the watch is not being updated while in the background, the complication is not being updated at all. Part of my confusion is I assumed CloudKit was meant to make this more seamless with silent push notifications? I have the "Remote Notifications" capability enabled on my WatchApp. It seems that only works while the app is in the foreground though. This seems very limiting when you have a complication that depends on the Watch app's Core Data state. I have a few things to work around this with mixed success: "Wake" the watch app explicitly when records are changed on the iPhone app using WatchConnectivityManager. The hope is that by waking the watch app, it will sync with iCloud. This either isn't working or intermittenly works. It is also not clear to me that by activating the watch app, that it will trigger records to sync. I wish there were a way to ask Core Data to sync explicitly. Whenever the Apple watch app wakes in the last step, ask it to WidgetCenter to reload the widget. This process feels convoluted and seems to negate some of the the benefits of CloudKit to synchronize data which I thought would be baked into this process. Any thoughts on a better approach to all this?
3
1
1.2k
Sep ’23
CloudKit Stopped Syncing after adding new Entities
Can someone please shed some light? I have an app that uses Core Data and CloudKit, up until the last version, I was able to sync data between devices but now after I added two new Entities for some reason it stopped syncing between devices. Here is how I did the change: Created a new Core Data container. Added the new Entities and their Attributes Tested the new Entities locally to be able to send the new schema to CloudKit. Went to CloudKit and made sure that the new Entities and Attributes were reflected on the Developent database. Deploy Schema Cahnges. Went to the Production database to make sure the new schema was deployed; and it was, both databases look the same. Testing: Tested in the simulator and with a real device and everything syncs, even the new Entities. If I download the app from the App Store on two different devices they do NOT sync. Based on the procedure I'm describing above, is there any important step I may have missed when doing the migration? I'm not sure if this is related to the syncing issue but after testing a few times, I no longer can turn the iCloud on, I get the following message when I try to turn iCloud Sync On. CoreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate resetAfterError:andKeepContainer:]: <NSCloudKitMirroringDelegate: 0x282c488c0> - resetting internal state after error: Error Domain=NSCocoaErrorDomain Code=134410 "CloudKit setup failed because there is another instance of this persistent store actively syncing with CloudKit in this process." UserInfo={NSURL=file:///var/mobile/Containers/Data/Application/73F19BC7-4538-4098-85C7-484B36192CF3/Library/Application%20Support/CoreDataContainer.sqlite, NSLocalizedFailureReason=CloudKit setup failed because there is another instance of this persistent store actively syncing with CloudKit in this process., NSUnderlyingException=Illegal attempt to register a second handler for activity identifier com.apple.coredata.cloudkit.activity.setup.8D4C04F6-8040-445A-9447-E5646484521} Any idea of what could be wrong and preventing the devices from syncing? Any idea or suggestion is welcome. Thanks
3
0
1.7k
1w
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
601
May ’24
CloudKit backed SwiftData @Relationship
Hi, does anyone know how to get @Relationship in SwiftData to cascade to the CloudKit container? I've managed to get SwiftData classes to show up in CloudKit but they are not related in line with the @Relationship as per the example project: @Relationship(.cascade) var bucketListItem: [BucketListItem] = []` They are simply separate records. As result the cascade of deletes doesn't work. Any ideas?
2
0
766
Dec ’23
Enable Permissions (iCloud)
Greetings! In my application I request permission from the user to utilize iCloud. func requestPermission() { CKContainer.default().requestApplicationPermission([.userDiscoverability]) { [weak self] returnedStatus, _ in DispatchQueue.main.async { if returnedStatus == .granted { self?.permissionStatus = true } } } } How can I programatically ask for this permission again via a button? Sometimes a user may deny or disable this permission in error. Thank you! :)
2
0
520
Jul ’23
Limits of CloudKit Public Database
Hello! I would like my users to save short videos (under 30seconds 1080p) to the public database for all other users to download and view. Is this possible? Will I run into any storage pricing with Apple if I were to pursue this as my application backend? I am looking at other methods as well (user sharing from their private database) so I can implement video sharing. Is this feasible and worth pursuing?
2
0
1k
Jul ’23
The model configuration used to open the store is incompatible with the one that was used to create the store.
I have deleted the app and try to run the Xcode project again. How can I remove this error ? Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=134020 "The model configuration used to open the store is incompatible with the one that was used to create the store." UserInfo={NSAffectedObjectsErrorKey=<NSManagedObject: 0x6000021c5310>
2
1
1.3k
Oct ’23
How to sync NSPersistentCloudKitContainer in background after performing AppIntent from widget
I have an app that uses NSPersistentCloudKitContainer and a widget that displays a record. I want to add a button with interactive widgets in iOS 17 to modify the visible record via an AppIntent. When I do this the app logs: CoreData: debug: CoreData+CloudKit: -[NSCloudKitMirroringDelegate managedObjectContextSaved:](2945): <NSCloudKitMirroringDelegate: 0x2818002a0>: Observed context save: <NSPersistentStoreCoordinator: 0x280a05180> - <NSManagedObjectContext: 0x281a00410> It does not automatically sync this change to iCloud, not until I manually return the app to the foreground, even if I delay returning from the perform() function. Is there a way to sync NSPersistentCloudKitContainer while the app is in the background as a result of this change triggered in the widget? Thanks!
2
1
624
Jul ’23
CoreData data disappears locally after disabling iCloud in device Settings
I've built an app and got it working nicely with CoreData, and now I want to integrate it with CloudKit. I have made some minor changes to my code (namely updating NSPersistentContainer to NSPersistentCloudKitContainer and CloudKit works - I can see records appearing in the iCloud dashboard and I can modify records from the iCloud dashboard and the changes reflect on my device. Great. However, if I disable iCloud syncing via Settings on my device (without force-quitting my app) I notice a couple of things: When switching back to my app if I try and edit an entity I sometimes get an app crash If I quit and reload the app all my data has disappeared from my device (it still remains in iCloud). Is this expected behaviour? Ideally, what I would like, is that the data persists locally if a user has added records but then later decides to disable iCloud syncing on the app. Here's my code in case I've done anything funky with the implantation. It feels pretty simple, but maybe that's the problem. CoreDataManager.swift: class CoreDataManager { static let shared = CoreDataManager() lazy var persistentContainer: NSPersistentCloudKitContainer = { setupPersistentContainer() }() private func setupPersistentContainer() -> NSPersistentCloudKitContainer { print("setup") let container = NSPersistentCloudKitContainer(name: "TestApp") guard let storeDescription = container.persistentStoreDescriptions.first else { fatalError("Could not load store description.") } storeDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) storeDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) container.loadPersistentStores { (_, error) in if let error = error as NSError? { fatalError("Unresolved error when loading CoreData persistent stores: \(error), \(error.userInfo)") } } container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy return container } } The CoreDataManager class is then called from my main App.swift file when assigning the MOC: @main struct Main: App { // // MARK: Properties // @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate // CoreData context let moc = CoreDataManager.shared.persistentContainer.viewContext // // MARK: Initialisation // var body: some Scene { WindowGroup { Test() .environment(\.managedObjectContext, moc) } } } And finally the Test.swift (as a very basic example) struct Test: View { @FetchRequest(sortDescriptors: []) var people: FetchedResults<Person> var body: some View { List(people) { person in Text(person.name ?? "Unknown") } } } Any sage advice would be welcome as I'm tearing my hair out over this. Is my approach even correct/what's the expected behaviour here?
1
0
492
Jul ’23
Production and Testflight app coredata react as separate instance
I wanted to bring to your attention an issue recently identified regarding the accessibility of existing production core data on our TestFlight app. Following the completion of a core data migration process, accessing the aforementioned production data has become temporarily unavailable on the TestFlight platform. If I install the testflight app getting a new instance of core data. whereas in production another instance of core data. respectively after lightweight migration data are not merging.
0
0
495
Jul ’23
NSPersistentCloudKitContainer CKRecord conversion errors
I'm using NSPersistentCloudKitContainer with my app and everything has been working fine for the most part. However, every now and then I come across an entity that saves fine into core data but then can't sync to cloud kit and causes the entire cloud kit feature to stop working. The error happens when starting the app and looks like this: error: CoreData+CloudKit: -NSCloudKitMirroringDelegate _requestAbortedNotInitialized:: <NSCloudKitMirroringDelegate: 0x2820187e0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringImportRequest: 0x283a27930> 3CD51F2A-E632-4FF0-8B8C-C17DCB15A002' due to error: <CKError 0x281739a10: "Partial Failure" (2/1011); "Failed to modify some records"; uuid = 9C4B94E0-662F-4B75-894B-55AD51DE9C79; container ID = "iCloud.com.mrsdizzie.LaurasBooks"; partial errors: { 0A2C0554-254E-47AA-B2C5-58F6C1CA038E:(com.apple.coredata.cloudkit.share.164680EE-7664-4105-9039-2FA952A013AB:__defaultOwner__) = <CKError 0x28173a6a0: "Invalid Arguments" (12/2006); server message = "Cannot create or modify field 'CD_data_ckAsset' in record 'CD_ImageData' in production schema"; op = 065A25FC65E7BB30; uuid = 9C4B94E0-662F-4B75-894B-55AD51DE9C79> ... 3 "Batch Request Failed" CKError's omited ... }> The app is for keeping track of Books, so the basic data model is an entity named Book with a relationship named imageData. This maps to an entity named ImageData with a field named data. data is of type "binary data" and where the cover image for a particular book is stored. This has worked so far for hundreds of entries into core data and cloud kit, but every now and then I see an error like this in the console app and the only way to recover is delete the offending entry (either manually, or by removing the app which deletes all local data). I am now able to reproduce it with one particular entry on one device in production, but not sure how to proceed from there. Since all of this syncing and creation of CKRecords happens automatically via NSPersistentCloudKitContainer I'm not really sure what to do, how to recover, or how to get more details about what it doesn't like in this particular case. I've monitored NSPersistentCloudKitContainer.eventNotificationUserInfoKey for event errors but only get short errors like: CKError Domain: 2, Description: The operation couldn't be completed The production schema is up to date and hasn't changed. Most entries into the app work fine. It is only every so often with certain entries that this error happens. There is no obvious difference between entries that I can see. The image itself in this and other cases is under 1MB. Any advice appreciated. Thanks!
4
1
707
Jul ’23
Refresh view with new CloudKit records
Hello, I'm new to iOS development and I need help for working with CloudKit. I have an application that allows me to add, delete and display information stored in a CloudKit container. When I try to add a new record, this one can be visible into my CloudKit Console but if don't switch to a other view and back to my view (with my list of records) the record isn't displayed. How can I update my list to reflect directly the new record add to my container ? This is my code with split into different files (in attachment) Sets : define my record struct SetsView: list of my records AddSetView: add new records AddSetView-ViewModel : view model with my add function SetsView-ViewModel: view model with my fetch function Add function : func add() async throws { var newSet = set newSet.name = name newSet.code = code newSet.releaseDate = releaseDate newSet.numberOfCards = numberOfCards let record = try await db.save(newSet.set) guard let set = Set(record: record) else { return } setsDictionary[set.id!] = set print("Set added") } Fetch function : func fetchSets() async throws { let query = CKQuery(recordType: SetRecordKeys.type.rawValue, predicate: NSPredicate(value: true)) query.sortDescriptors = [NSSortDescriptor(key: "name", ascending: false)] let result = try await db.records(matching: query) // récupère les données qui correspondent aux critères let records = result.matchResults.compactMap { try? $0.1.get() } // Récupère les records sets.removeAll() records.forEach { record in sets.append(Set(record: record)!) } print("Sets fetched") print(sets) } Set.txt SetsView.txt AddSetView.txt AddSetView-ViewModel.txt SetsView-ViewModel.txt I try to add some print to figure out what's going on, but I don't understand. This is the console log for this scenario : open app without any data into the container > add a new record First, the fetch function is executed but there is no data into the container (it's logic) Second I add a new record (Set) : Into the CloudKit console the new Set is visible So for refresh my view with this record I need to re-call the fetch function. I tried many things but nothing works. Even if the fetch function is called, the new record is not retrieved. Do you have any idea how to solve this problem? Thanks for your help.
0
0
568
Jul ’23
User Name components
Trying to build an app that shares data across users, and one sanity check I was using was to check that the current user has granted permission to be looked up, and then I could display the user's name in the view. Previously, I could check the applicationPermissionStatus with CKContainer.applicationPermissionStatus(for:), and if it were not granted, I could request it with CKContainer.default().requestApplicationPermission. Both of those functions (and several others that i was using in my app) now pop up with the message: 'requestApplicationPermission' was deprecated in iOS 17.0: No longer supported. Please see Sharing CloudKit Data with Other iCloudUsers. Unfortunately, I have found no alternate way to get the user identity in the Documentation, although it is a fairly large section and it's possible I am overlooking it. Is there a way to display the user's name components?
1
0
479
Jul ’23
SwiftData cloud data update in real time?
Hey, I've been working with SwiftData for a while now and I'm currently in the process of adding iCloud functionality to my program. Everything works fine, but the data update only after running the app twice or restarting it twice in the simulator. It would be better if this could be done in real time or at the push of a button. Does anyone have an idea how to implement this? The devices send a message in the background (that there is an update) or? Can you access it somehow and the @Query update?
0
0
421
Jul ’23
Potential problem with synching users' private CloudKit with NSPersistentCloudKitContainer
Imagine I have a game with new levels every day. Users play my game and their progress is saved in Core Data, which is then synchronized with CloudKit via NSPersistentCloudKitContainer. Users' progress is about 500Kb for each level/day. That's 5 Mb in 10 days. Or 182 Mb in a year. If the user plays my game for a year, gets a new iPhone, and installs my app again — will the NSPersistentCloudKitContainer eventually download all 182 Mb of users' data!?
1
0
421
Jul ’23