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

SwiftData: Model Container fails completely when CloudKit storage is full
struct ModelContainerSetup { static let shared = ModelContainerSetup() private static let containerIdentifier = "iCloud.Journal" func setupModelContainer() -> ModelContainer { let schema = Schema([User.self]) let modelConfiguration = ModelConfiguration( schema: schema, isStoredInMemoryOnly: false, cloudKitDatabase: .private(Self.containerIdentifier) ) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } } **Expected Behavior: ** When CloudKit storage is full, the app should continue functioning with local storage Data should persist locally even if cloud sync fails Sync should resume when storage becomes available **Actual Behavior: ** ModelContainer initialization fails completely Local data also stops getting saved **Environment: ** iOS 17.0+ SwiftData Private CloudKit database Ideal Behaviour: When iCloud fails, the data should still be saved locally. I do not want to have two different containers so that I can maintain data consistency.
0
0
32
5h
Silent push notifications not working on some iOS devices
I send APNs notifications to my devices with the CloudKit dashboard. I test with two devices; Device with Silent Push Working Successfully: iOS version 16.5.1 (c), Model iPhone Xs Silent Push Failed Device: iOS version 15.3.1, Model iPhone Xr Normal alert notifications work successfully on both devices. But I can't see any log in my project even though silent push is sent successfully on one device. What I've Checked: content-available is set to 1. My app is not in kill state, it is in foreground or pending in the background. When I send simple notifications, I can see logs in my swift project and notifications on physical devices without any problem. No, my certificate has not expired and if there was a problem with it, I would not be able to see the normal notifications. My phone is not in power saving mode and the “Background App Refresh” option is turned on in the app's settings. Both devices in charging state. App capabilities: Background Modes is enabled with Remote Notifications, Background Fetch, Background Processing. CloudKit Dashboard After Sending Silent Push: My AppDelegate Class In Swift Project: import SwiftUI import UIKit import UserNotifications class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in if granted { DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } return true } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) } let token = tokenParts.joined() print("Device Token: \(token)") } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("Failed to register: \(error)") } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { logInfo("Received Push Notification: \(userInfo)") if let aps = userInfo["aps"] as? [String: AnyObject], aps["content-available"] as? Int == 1 { logInfo("This is a silent push notification") //DO SOME WORK completionHandler(.newData) } completionHandler(.newData) } }
2
0
52
3h
CloudKit + SwifData setup
Hey folks, I'm having an issue where iCloud sync is only working in the Development environment, not on Prod. I have deployed the schema to Prod through the CloudKit console, although I did it after the app went live on the AppStore. Even though the two schema are identical, iCloud sync just doesn't work on Prod. Things I tried on the code side: Initially I did the most basic SwiftData+CloudKit setup: var modelContainer: ModelContainer { let schema = Schema([Book.self, Goal.self]) let config = ModelConfiguration(isStoredInMemoryOnly: false, cloudKitDatabase: doesUserSyncToiCloud ? .automatic : .none) var container: ModelContainer do { container = try ModelContainer(for: schema, configurations: config) } catch { fatalError() } return container } var body: some Scene { WindowGroup { AnimatedSplashScreen { MainTabView() } } .modelContainer(modelContainer) } This is enough to make iCloud sync work at the Development level. Then when I noticed the issues on Prod I did some digging and found this on the Docs (https://developer.apple.com/documentation/swiftdata/syncing-model-data-across-a-persons-devices): let config = ModelConfiguration() do { #if DEBUG // Use an autorelease pool to make sure Swift deallocates the persistent // container before setting up the SwiftData stack. try autoreleasepool { let desc = NSPersistentStoreDescription(url: config.url) let opts = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.example.Trips") desc.cloudKitContainerOptions = opts // Load the store synchronously so it completes before initializing the // CloudKit schema. desc.shouldAddStoreAsynchronously = false if let mom = NSManagedObjectModel.makeManagedObjectModel(for: [Trip.self, Accommodation.self]) { let container = NSPersistentCloudKitContainer(name: "Trips", managedObjectModel: mom) container.persistentStoreDescriptions = [desc] container.loadPersistentStores {_, err in if let err { fatalError(err.localizedDescription) } } // Initialize the CloudKit schema after the store finishes loading. try container.initializeCloudKitSchema() // Remove and unload the store from the persistent container. if let store = container.persistentStoreCoordinator.persistentStores.first { try container.persistentStoreCoordinator.remove(store) } } } #endif modelContainer = try ModelContainer(for: Trip.self, Accommodation.self, configurations: config) } catch { fatalError(error.localizedDescription) } I've no idea why Apple would include this CoreData setup in a SwiftData documentation, but I went ahead and adapted it to my code as well. I see now that some new "assets" were added to my Development schema, but I'm afraid to deploy these changes to Prod, since I'm not even confident that this CoreData setup is necessary in a SwiftData app. Does anyone have any thoughts on this? Have you run into similar issues? Any help would be much appreciated; thanks!
0
0
48
1d
Sync SwiftData via CloudKit on App Start
I have an app that uses SwiftData with CloudKit to synchronize data across a users devices. I'm able to replicate data created on one device on another and when removing data, it is also removed on the other device. So, I know that SwiftData and CloudKit are configured correctly. What I'd like to do though, is to ensure that if a user installs the app on an additional device, that the data is synchronized upon app start. When testing my app on a third device, via TestFlight, there was no data in the app upon launch even though all three devices are using the same Apple account (e.g. Apple ID). What is the best way to achieve this?
4
1
95
2d
Core Data Error - "NSCocoaErrorDomain" - code: 134060
Hi, I am implementing the synchronisation of SwiftData with CloudKit as described in the Apple Documentation titled - "Syncing model data across a person’s devices." My app runs fine on iPhone without activating CloudKit under "Signing and Capabilities" option. But when activated, I get a CoreData error with a code: 134060. My app is in development stage. The following is the code snippet for your reference taken from the main structure adopting the App protocol. init() { do { #if DEBUG let schema = Schema([ Debit.self, Credit.self, ]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) // Use an autorelease pool to make sure Swift deallocates the persistent // container before setting up the SwiftData stack. try autoreleasepool { let desc = NSPersistentStoreDescription(url: modelConfiguration.url) let opts = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.sureshco.MyFirstApp") desc.cloudKitContainerOptions = opts // Load the store synchronously so it completes before initializing the CloudKit schema. desc.shouldAddStoreAsynchronously = false if let mom = NSManagedObjectModel.makeManagedObjectModel(for: [ Debit.self, Credit.self, ]) { let container = NSPersistentCloudKitContainer(name: "MyFirstApp", managedObjectModel: mom) container.persistentStoreDescriptions = [desc] container.loadPersistentStores {_, err in if let err { fatalError(err.localizedDescription) } } // Initialize the CloudKit schema after the store finishes loading. try container.initializeCloudKitSchema() // Remove and unload the store from the persistent container. if let store = container.persistentStoreCoordinator.persistentStores.first { try container.persistentStoreCoordinator.remove(store) } } } #endif sharedModelContainer = try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError(error.localizedDescription) } } Any help will be greatly appreciated! Regards Suresh.
0
0
145
4d
SiftData with CloudKit testing
I'm trying to add Cloud Kit integration to SwiftData app (that is already in the App Store, btw). When the app is installed on devices that are directly connected to Xcode, it works (a bit slow, but pretty well). But when the app is distributed to Testflight internal testers, the synchronization doesn't happen at all. So, is this situation normal and how can I test apps with iCloud integration properly?
1
0
103
11h
MacOS CloudKit production environment is not working properly
My macOS app is developed using SwfitUI, SwiftData, and CloudKit. In the development environment, CloudKit works well. Locally added models can be quickly viewed in the CloudKit Console. macOS app and iOS app with the same BundleID can also synchronize data normally when developing locally. However, in the production environment, the macOS app cannot synchronize data with iCloud. But iOS app can. The models added in the production environment are only saved locally and cannot be viewed in CloudKit Console Production. I am sure I have configured correctly, container schema changes to deploy to the Production environment. I think there may be a problem with CloudKit in macOS. Please help troubleshoot the problem. I can provide you with any information you need. var body: some Scene { WindowGroup { MainView() .frame(minWidth: 640, minHeight: 480) .environment(mainViewModel) } .modelContainer(for: [NoteRecord.self]) } I didn't do anything special. I didn’t do anything special. I just used SwiftData hosted by CloudKit.
2
0
126
2d
Avoiding deletion of referenced records
Let's say I have a CloudKit database schema where I have records of type Author that are referenced by multiple records of type Article. I want to delete an Author record if no Article is referencing it. Now consider the following conflict: device A deleted the last Article referencing Author #42 device B uploads a new Article referencing Author #42 at the same time The result should be that Author #42 is not deleted after both operations are finished. But both device don't know from each other changes. So either device B could miss that device A deleted the author. Or device A could have missed that a new Article was uploaded and therefore the Author #42 was deleted right after the upload of device B. I though about using a reference count first. But this won't work if the ref count is part of the Author record. This is because deletions do not use the changeTag to detect lost updates: If device A found a reference count 0 and decides to delete the Author, it might miss that device B incremented the count meanwhile. I currently see two alternatives: Using a second record that outlives the Author to keep the reference count and using an atomic operation to update and delete it. So if the update fails, the delete would fail either. Always adding a new child record to the Author whenever a reference is made. We could call it ReferenceToken. Since child records may not become dangling, CloudKit would stop a deletion, if a new ReferenceToken sets the parent reference to the Author. Are there any better ways doing this?
0
0
94
1w
Display name for CloudKit container in the "Manage Storage" view of Settings
How can I set the display name of the CloudKit container in Settings -> iCloud -> Manage Storage. I have multiple containers, some legacy, and some for certain modules that are shared among a suite of apps. The problem is all Containers show the same name so it is not possible to advise a user which containers are safe to delete. I am using NSPersistentCloudKitContainer.
0
0
71
1w
NSPersistentCloudKitContainer not saving 50% of the time
I'm using NSPersistentCloudKitContainer to save, edit, and delete items, but it only works half of the time. When I delete an item and terminate the app and repoen, sometimes the item is still there and sometimes it isn't. The operations are simple enough: moc.delete(thing) try? moc.save() Here is my DataController. I'm happy to provide more info as needed class DataController: ObservableObject { let container: NSPersistentCloudKitContainer @Published var moc: NSManagedObjectContext init() { container = NSPersistentCloudKitContainer(name: "AppName") container.loadPersistentStores { description, error in if let error = error { print("Core Data failed to load: \(error.localizedDescription)") } } #if DEBUG do { try container.initializeCloudKitSchema(options: []) } catch { print("Error initializing CloudKit schema: \(error.localizedDescription)") } #endif moc = container.viewContext } }
1
0
100
1w
Questions about CloudKit cross-device synchronization
The same macOS app is logged into the same iCloud account on two Macs. The apps on both devices can sync data with iCloud, but the data between them is isolated. When I was developing, I just enabled the CloudKit(SwiftData host in iCloud) capability and did not do anything special. I thought that the same app and the same iCloud account should sync the same data between different devices. Why is the cloud data on these two Macs isolated?
1
0
115
1w
CKSyncEngine and desiredKeys
I have a CKRecord that references an CKAsset. If I understand it correctly, CKSyncEngine would download the asset every time the record has changed on the server. (Of course it would try to use the local asset cache, but worst-case it might be already flushed) The documentation for CKAsset says that asset downloads can be prevented by limiting the requested record keys using the desiredKeys property on the fetch operation. But I don't see any possibility to set this property when using CKSyncEngine. Did I miss something? Are there any alternatives?
2
0
63
1w
CoreData iCloud Can't Sync
Only development environment can real sync. But product environment can't sync. And when run my device show this error: CoreData: Already have a mirrored relationship registered for this key: CD_M2M_Event_items:B269B612-37A6-4ED7-9FDB-601E88BF56A8:8DC64E4A-E893-4465-8B21-48CF1C52A4BC <NSCKMirroredRelationship: 0x302bb9950> (entity: NSCKMirroredRelationship; id: 0xa049af3fb0190928 <x-coredata://BEB6E57C-891C-4E71-B92F-7BAA0844913E/NSCKMirroredRelationship/p1747>; data: { cdEntityName = Event; ckRecordID = "B5908A8A-079E-482C-9F2E-1309BF071F0E"; ckRecordSystemFields = nil; isPending = 0; isUploaded = 0; needsDelete = 0; recordName = "B269B612-37A6-4ED7-9FDB-601E88BF56A8"; recordZone = "0xa049af3f6a5909a8 <x-coredata://BEB6E57C-891C-4E71-B92F-7BAA0844913E/NSCKRecordZoneMetadata/p1>"; relatedEntityName = Item; relatedRecordName = "8DC64E4A-E893-4465-8B21-48CF1C52A4BC"; relationshipName = items; }) <decode: bad range for [%@] got [offs:941 len:665 within:0]> And my product core data sync data only to October 24, 2024. The data before October 24 was synchronized normally, Nothing after October 24 is synced.
0
0
97
1w
Getting error "Failed user key sync" when trying to connect to CloudKit after Xcode 16.1 update / iOS 18.1
Hey there, I’m feeling pretty desperate at this point, as my most recent update to Xcode 16.1 and the new 18.1 simulators has basically made it impossible for me to work on my apps. The same app and same code run fine in the 18.0 simulators with the same iCloud account logged in. I’ve tried multiple simulators with the same results, even on different computers. I’ve also tried logging in repeatedly without any luck. The CloudKit database logs don’t show any errors or suspicious entries. Reinstalling the app on the simulator doesn't help either. Whenever I launch the application in Xcode, I'm getting: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1240): <NSCloudKitMirroringDelegate: 0x600003d213b0>: Failed to set up CloudKit integration for store: <NSSQLCore: 0x103f124e0> (URL: file:///Users/kerstenbroich/Library/Developer/CoreSimulator/Devices/57BC78CE-DB2A-4AC0-9D7A-43C386305F56/data/Containers/Data/Application/EFDE9B05-0584-47C5-80AE-F2FF5994860C/Library/Application%20Support/Model.sqlite) <CKError 0x600000d3dfe0: "Partial Failure" (2/1011); "Failed to modify some record zones"; partial errors: { com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x600000d7c090: "Internal Error" (1/5000); "Failed user key sync"> }> error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate recoverFromError:](2310): <NSCloudKitMirroringDelegate: 0x600003d213b0> - Attempting recovery from error: <CKError 0x600000d3dfe0: "Partial Failure" (2/1011); "Failed to modify some record zones"; partial errors: { com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x600000d7c090: "Internal Error" (1/5000); "Failed user key sync"> }> error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _recoverFromPartialError:forStore:inMonitor:]_block_invoke(2773): <NSCloudKitMirroringDelegate: 0x600003d213b0>: Found unknown error as part of a partial failure: <CKError 0x600000d7c090: "Internal Error" (1/5000); "Failed user key sync"> error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _recoverFromPartialError:forStore:inMonitor:](2820): <NSCloudKitMirroringDelegate: 0x600003d213b0>: Error recovery failed because the following fatal errors were found: { "<CKRecordZoneID: 0x600000d62340; zoneName=com.apple.coredata.cloudkit.zone, ownerName=__defaultOwner__>" = "<CKError 0x600000d7c090: \"Internal Error\" (1/5000); \"Failed user key sync\">"; } Any help/ideas would be much appreciated, because I have no clue what to try next. Thanks a lot!
3
3
236
4d
CloudKit error
I'm continually getting an error with a new CloudKit container when I try to save data. error: Couldn't get container configuration from the server for container "iCloud.com.***.***" here's the class: private var db = CKContainer(identifier: "iCloud.com.***.***").privateCloudDatabase func addTask(taskItem: TaskItem) async throws { checkStatus() do { try await db.save(taskItem.record) } catch { print("error: \(error.localizedDescription)") } } func checkStatus() { let id = CKContainer(identifier: "iCloud.com.***.***").containerIdentifier print(id ?? "unknown") Task { let status = try await CKContainer(identifier: "iCloud.com.***.***").accountStatus() switch status { case .available: print("available") case .noAccount: print("no account") case .restricted: print("restricted") case .couldNotDetermine: print("could not determine") case .temporarilyUnavailable: print("temporarily unavailable") @unknown default: break } } } The account status reports as available but gives the error on an attempt to save.. I'm trying to work out what I might be doing wrong..
0
0
132
2w
CKShare different targets
Hello, I`m working on an app that uses CloudKit and CKShare, but the app has 2 different targets, one for professional and one for patients, and theoretically the target of the professional sends the CKShare and the target of the patient should accept, but the ckshare tries to always open the target of the profissional, I would like to know if the are any way to configure the CKShare to oppen the target od the patients
1
1
117
2w
How are items in CKSyncEngine.State.pendingDatabaseChanges removed after they haven been saved to cloud?
While reading CkSyncEngine demo project code, I don't find the code to remove items in syncEngine.state.pendingRecordZoneChanges explicitly. I suspect it might occur in two possible places: nextRecordZoneChangeBatch() or ``nextRecordZoneChangeBatch()`, but I can't figure out how it occurs. nextRecordZoneChangeBatch() has the following code: let batch = await CKSyncEngine.RecordZoneChangeBatch(pendingChanges: changes) { recordID in if let contact = contacts[recordID.recordName] { let record = contact.lastKnownRecord ?? CKRecord(recordType: Contact.recordType, recordID: recordID) contact.populateRecord(record) return record } else { // We might have pending changes that no longer exist in our database. We can remove those from the state. syncEngine.state.remove(pendingRecordZoneChanges: [ .saveRecord(recordID) ]) return nil } } (I'll ignore the syncEngine.state.remove(pendingRecordZoneChanges:) in the else clause, because it's unrelated) Could it be that CKSyncEngine.RecordZoneChangeBatch.init(pendingChanges:,recordProvider:) automatically remove a CKRecord when the recordProvider: closure returns a non-nil value? I checked its document, but it doesn't say anything about this. Thanks for any help.
0
0
177
2w
A question on account change handler code in CKSyncEngine demo project
I have a quesiton on .accountChange handler code in CKSyncEngine demo project. Below is the code in handleAccountChange(): if shouldDeleteLocalData { try? self.deleteLocalData() // This error should be handled, but we'll skip that for brevity in this sample app. } if shouldReUploadLocalData { let recordZoneChanges: [CKSyncEngine.PendingRecordZoneChange] = self.appData.contacts.values.map { .saveRecord($0.recordID) } self.syncEngine.state.add(pendingDatabaseChanges: [ .saveZone(CKRecordZone(zoneName: Contact.zoneName)) ]) self.syncEngine.state.add(pendingRecordZoneChanges: recordZoneChanges) } IMHO, when user switches account, the most important thing is to reload data from the new account's document folder. However, I can't see this is done anywhere. In above code, if shouldDeleteLocalData is false, self.appData would still hold the previous account's local data. That seems very wrong. Am I missing something? It would be best if iOS restarts all applications when user switches account. If that's not the case (I guess so, otherwise there is no point to handle .accountChange in the app), I think application should implement an API to re-initialize itself. EDIT: after looking at the code again, I realize that the following code makes sure shouldDeleteLocalData is always true when user switching accounts. So the code doesn't leak the previous account's data, though I still think it has an issue - it doesn't load the new account's data. case .switchAccounts: shouldDeleteLocalData = true shouldReUploadLocalData = false
4
0
189
2w