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 Migration: Keeps failing at the end of willMigrate
I've been trying to setup a successful migration, but it keeps failing with this error: NSCloudKitMirroringDelegate are not reusable and should have a lifecycle tied to a given instance of NSPersistentStore. I can't find any information about this online. I added breakpoints throughout the code in willMigrate, and it originally failed on this line: try? context.save() I removed that, and it still failed. After I reload the app, it doesn't run the migration again and the app loads successfully. I figured since it crashed, it would keep trying, but I guess not. Here's how my migration is setup. enum MigrationV1ToV2: SchemaMigrationPlan { static var schemas: [any VersionedSchema.Type] { [SchemaV1.self, SchemaV2.self] } static var stages: [MigrationStage] { [stage] } static let stage = MigrationStage.custom( fromVersion: SchemaV1.self, toVersion: SchemaV2.self, willMigrate: { context in // Get cycles let cycles = try? context.fetch(FetchDescriptor<SchemaV1.Cycle>()) if let cycles { for cycle in cycles { // Create new recurring objects based on what's in the cycle for income in cycle.income { let recurring = SchemaV2.Recurring(name: income.name, frequency: income.frequency, kind: .income) recurring.addAmount(.init(date: cycle.startDate, amount: income.amount)) context.insert(recurring) } for expense in cycle.expenses { let recurring = SchemaV2.Recurring(name: expense.name, frequency: expense.frequency, kind: .expense) recurring.addAmount(.init(date: cycle.startDate, amount: expense.amount)) context.insert(recurring) } for savings in cycle.savings { let recurring = SchemaV2.Recurring(name: savings.name, frequency: savings.frequency, kind: .savings) recurring.addAmount(.init(date: cycle.startDate, amount: savings.amount)) context.insert(recurring) } for investment in cycle.investments { let recurring = SchemaV2.Recurring(name: investment.name, frequency: investment.frequency, kind: .investment) recurring.addAmount(.init(date: cycle.startDate, amount: investment.amount)) context.insert(recurring) } } //try? context.save() } else { print("The cycles were not able to be fetched.") } }, didMigrate: { context in // Get new recurring objects let newRecurring = try? context.fetch(FetchDescriptor<SchemaV2.Recurring>()) if let newRecurring { for recurring in newRecurring { // Get all recurring with the same name and kind let sameName = newRecurring.filter({ $0.name == recurring.name && $0.kind == recurring.kind }) // Add amount history to recurring object, and then remove matching for match in sameName { recurring.amountHistory.append(contentsOf: match.amountHistory) context.delete(match) } } //try? context.save() } else { print("The new recurring objects could not be fetched.") } } ) } Here's is my modelContainer in the app file. There is a fatal error occurring here that's crashing the app. var sharedModelContainer: ModelContainer = { let schema = Schema(versionedSchema: SchemaV2.self) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) do { return try ModelContainer( for: schema, migrationPlan: MigrationV1ToV2.self, configurations: [modelConfiguration] ) } catch { fatalError("Could not create ModelContainer: \(error)") } }() Does anyone have any suggestions for this? EDIT: I found this error in the console that may be relevant. BUG IN CLIENT OF CLOUDKIT: Registering a handler for a CKScheduler activity identifier that has already been registered (com.apple.coredata.cloudkit.activity.export.8F7A1261-4324-40B4-B041-886DF36FBF0A). CloudKit setup failed because it couldn't register a handler for the export activity. There is another instance of this persistent store actively syncing with CloudKit in this process. And here is the fatal error Fatal error: Could not create ModelContainer: SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer, _explanation: nil)
0
0
46
1d
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
53
2d
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
68
2d
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
59
3d
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
110
4d
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
160
6d
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?
2
0
124
1d
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
131
4d
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
99
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
75
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
104
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
118
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
67
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
103
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
244
6d
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
136
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
121
3w
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
179
3w