iCloud & Data

RSS for tag

Learn how to integrate your app with iCloud and data frameworks for effective data storage

CloudKit Documentation

Post

Replies

Boosts

Views

Activity

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
150
Nov ’24
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
194
Nov ’24
SwiftData know how specific information
Re SwiftData: is my understanding correct : generally speaking and by default insert method inserts objects into the context and context automatically persist - e.g. inserts them into container while the delete method does not - it only deletes from context and context does not delete them from the container unless save is called ? It is not clear from the documentation nor from the definitions : public func delete<T>(model: T.Type, where predicate: Predicate<T>? = nil, includeSubclasses: Bool = true) throws where T : PersistentModel //How can I test it ? I’m keen to learn where I can confirm this in Apple’s documentation or official articles, code definitions, apart from experimenting or consulting third-party materials. Where does it explicitly state that SwiftData includes an automatic saving feature but does not offer automatic deletion? "Meet SwiftData" (WWDC23): Around the 14:30 mark, Apple mentions that SwiftData automatically saves changes "at opportune moments." But nothing is advised re deleting ? Are we supposed to be taking hints : "Build an app with SwiftData" (WWDC23): This session demonstrates using context.save() to persist changes after deleting an object, implies the idea that deletion isn't automatic How to truly learn if you do not have official materials ? This is exact Science, not archeology or history. I feel like a speleologist.
1
0
206
Oct ’24
Core Data boilerplate project causes Fatal Error
I'm using Xcode 16 and SwiftUI targeting iOS 18. I'm new to Core Data, and when I create a new project and select to use Core Data as storage, I get boilerplate code for it. The problem is that when I try to see the preview without any change to the code, I get a Fatal Error: CrashReportError: Fatal Error in Persistence.swift Test crashed due to fatalError in Persistence.swift at line 52. Unresolved error Error Domain=NSSQLiteErrorDomain Code=8 "(null)" UserInfo={NSFilePath=/Users/monni/Library/Developer/Xcode/UserData/Previews/Simulator Devices/D0D98B5B-7E6F-4DC3-B16A-34D6D2958558/data/Containers/Data/Application/A98879A6-46F5-4E29-B2D7-AD294F1EFFD0/Library/Application Support/Test.sqlite, NSSQLiteErrorDomain=8}, ["NSSQLiteErrorDomain": 8, "NSFilePath": /Users/monni/Library/Developer/Xcode/UserData/Previews/Simulator Devices/D0D98B5B-7E6F-4DC3-B16A-34D6D2958558/data/Containers/Data/Application/A98879A6-46F5-4E29-B2D7-AD294F1EFFD0/Library/Application Support/Test.sqlite] When I try to open the SQLite database there are no entities in it. I have also tried xcrun simctl --set previews delete all, but with no luck.
2
1
186
Oct ’24
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
218
Oct ’24
iOS 18 Core Data and CloudKit Sync Issue with NSPersistentCloudKitContainer
After upgrading to iOS 18, my Core Data stack using NSPersistentCloudKitContainer in a shared App Group container stopped syncing correctly. The persistent store configuration, which previously worked in iOS 17, now experiences delayed or missing sync updates between devices. Then the app freezes and writes terminal the same error detail (which I provided) too many times. The debug logs from the CloudKit mirroring delegate (NSCloudKitMirroringDelegate) show repetitive notifications but no updates in persistent history. Additionally, the persistent history tracking key appears unresponsive to local changes, causing transactions to fail in updating or syncing as expected. Key setup details: Core Data is set up within an App Group container using NSPersistentCloudKitContainer. NSPersistentHistoryTrackingKey and NSPersistentStoreRemoteChangeNotificationPostOptionKey options are set to true. Any insights into changes in iOS 18 Core Data or CloudKit handling with NSPersistentCloudKitContainer, especially around history tracking and sync delays, would be greatly appreciated. Thank you. Error Detail file:///private/var/mobile/Containers/Shared/AppGroup/BF95D309-EBE9-485E-B5CE-AA17097F7B60/[AppName]Database.sqlite CoreData: debug: CoreData+CloudKit: -[NSCloudKitMirroringDelegate managedObjectContextSaved:](3123): <NSCloudKitMirroringDelegate: 0x3032b4870>: Observed context save: <NSPersistentStoreCoordinator: 0x302694bd0> - <NSManagedObjectContext: 0x3036b1a00> CoreData: debug: CoreData+CloudKit: -[NSCloudKitMirroringDelegate remoteStoreDidChange:](3166): <NSCloudKitMirroringDelegate: 0x3032b4870>: Observed remote store notification: <NSPersistentStoreCoordinator: 0x302694bd0> - 090C4244-0101-4DEF-90D6-1260570F47A5 - <NSPersistentHistoryToken - { "090C4244-0101-4DEF-90D6-1260570F47A5" = 9; }> - Persistence.swift struct PersistenceController { let container: NSPersistentCloudKitContainer static let shared = PersistenceController() static var preview: PersistenceController = {PersistenceController()}() init() { container = NSPersistentCloudKitContainer(name: "[AppName]") // Configure CloudKit for the default container if let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.[CompanyName].[AppName]") { let storeURL = url.appendingPathComponent("[AppName]Database.sqlite") let description = container.persistentStoreDescriptions.first description?.url = storeURL description?.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) description?.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) container.persistentStoreDescriptions = [description].compactMap { $0 } } container.loadPersistentStores { (storeDescription, error) in if let error = error as NSError? { fatalError("Unresolved error \(error), \(error.userInfo)") } } container.viewContext.automaticallyMergesChangesFromParent = true container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy } }
0
1
248
Oct ’24
Persist app state across reinstalls/multiple devices
So I’m trying to setup an existing app to work with iCloud syncing. The syncing part seems to be working for the most part. When the app is first installed it sets up some data locally. Throughout the life of the app additional data is added through updates. There is a user default setup that stores the current data version, then compares it with the new version. If it’s newer, then loads the additional data. The issue I’ve got is a user can delete the app and reinstall, or install on another device which has that data version as 0, prompting another import even though the data in the cloud is current version, resulting in duplicate data once the sync is done. How can I persist that version data? I’ve seen NSUbiquitousKeyValueStore which seems to be a cloud based version of user defaults, but it says not to rely on it if it’s critical to app functions
0
0
137
Oct ’24
SwiftData ModelConfigurations always sync to iCloud if one of them has iCloud enabled
I'm facing a weird issue with SwiftData. I want to have one database that's local to the device and one that syncs to iCloud. In this example, LTRLink should be synced via iCloud while LTRMetadata should stay on-device only. I've it configured like the following: let schema = Schema([LTRLink.self, LTRMetadata.self]) let cloudkitConfiguration = ModelConfiguration("Remote", schema: schema, url: FileManager.remoteDatabaseFolderURL.appending(path: "Remote.sqlite"), cloudKitDatabase: .private("iCloud.com.xavimoll.abyss3")) let localConfiguration = ModelConfiguration("Local", schema: schema, url: FileManager.localDatabaseFolderURL.appending(path: "Local.sqlite"), cloudKitDatabase: .none) return try ModelContainer(for: schema, configurations: [cloudkitConfiguration, localConfiguration]) For some reason, when I create the iCloud schema, both models end up appearing as records on iCloud. I create the schema like this: let schema = Schema([LTRLink.self, LTRMetadata.self]) let cloudkitConfiguration = ModelConfiguration("Remote", schema: schema, url: FileManager.remoteDatabaseFolderURL.appending(path: "Remote.sqlite"), cloudKitDatabase: .private("iCloud.com.xavimoll.abyss3")) #if DEBUG // Needed to create the schema on iCloud try autoreleasepool { let desc = NSPersistentStoreDescription(url: cloudkitConfiguration.url) let opts = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudkitConfiguration.cloudKitContainerIdentifier!) desc.cloudKitContainerOptions = opts desc.shouldAddStoreAsynchronously = false if let mom = NSManagedObjectModel.makeManagedObjectModel(for: [LTRLink.self]) { let container = NSPersistentCloudKitContainer(name: "Remote", managedObjectModel: mom) container.persistentStoreDescriptions = [desc] container.loadPersistentStores {_, err in if let err { fatalError(err.localizedDescription) } } try container.initializeCloudKitSchema() if let store = container.persistentStoreCoordinator.persistentStores.first { try container.persistentStoreCoordinator.remove(store) } } } #endif let localConfiguration = ModelConfiguration("Local", schema: schema, url: FileManager.localDatabaseFolderURL.appending(path: "Local.sqlite"), cloudKitDatabase: .none) return try ModelContainer(for: schema, configurations: [cloudkitConfiguration, localConfiguration]) The logic to initialize the CloudKit schema follows the documentation found here: https://developer.apple.com/documentation/swiftdata/syncing-model-data-across-a-persons-devices#Initialize-the-CloudKit-development-schema It looks like setting cloudKitDatabase: .none on the init for the ModelConfiguration doesn't do anything, and ends up being synced with iCloud either way. When I go to the iCloud console, I see the following: Does anyone know if there's any workaround that would allow me to have two databases where only one of them syncs to iCloud when using SwiftData?
1
0
288
Oct ’24
SwiftUI previews and CloudKit sharing
The SwiftUI templates provided by Xcode typically create an in-memory store for preview purposes. I started from one of these templates and added the necessary code for working with CloudKit shares, but now the existing preview store creation gets runtime errors I'm struggling to understand. The ultimate error is: FAULT: NSInternalInconsistencyException: Unsupported feature in this configuration; { store = "<NSSQLCore: 0x12e26b170> (URL: file:///dev/null)"; } There are other things in the log like: warning: Multiple NSEntityDescriptions claim the NSManagedObject subclass 'Trip' so +entity is unable to disambiguate. This might be due in part to the normal full stack being instantiated during a unit test, but that was the only way I could step through the code to try to see what was causing the SwiftUI preview to crash. I can't build the full core data stack as normal, because then the unit tests and previews pollute the real store.
1
0
228
Oct ’24
CloudKit sharing limits?
When you share records, they get put into a new zone. Creating a zone for the share makes sense to me, but I thought I read that there was a limit to the number of zones one could have (something like 1024). Does this mean a user can’t share more than 1024 separate items with 1024 different people? I assume any other items shared with the same group end up in an existing zone.
0
0
164
Oct ’24
Thumbnails for images saved in core data
I'm trying to look at what the best way to do thumbnails for images that are saved in core data, which are being synced across multiple devices. I know I can save a lower quality version into core data, but I'm wondering if there's a better way of doing it. I've come across quick look thumbnailing which looks like what I want, but I'm not sure if it can be adapted for core data as its using file paths, whereas the images are stored in a data type property in core data. From what I can tell, I'd have to save the image locally, produce the thumbnail, then delete the local image
0
0
150
Oct ’24
SwiftData updates in the background are not merged in the main UI context
Hello, SwiftData is not working correctly with Swift Concurrency. And it’s sad after all this time. I personally found a regression. The attached code works perfectly fine on iOS 17.5 but doesn’t work correctly on iOS 18 or iOS 18.1. A model can be updated from the background (Task, Task.detached or ModelActor) and refreshes the UI, but as soon as the same item is updated from the View (fetched via a Query), the next background updates are not reflected anymore in the UI, the UI is not refreshed, the updates are not merged into the main. How to reproduce: Launch the app Tap the plus button in the navigation bar to create a new item Tap on the “Update from Task”, “Update from Detached Task”, “Update from ModelActor” many times Notice the time is updated Tap on the “Update from View” (once or many times) Notice the time is updated Tap again on “Update from Task”, “Update from Detached Task”, “Update from ModelActor” many times Notice that the time is not update anymore Am I doing something wrong? Or is this a bug in iOS 18/18.1? Many other posts talk about issues where updates from background thread are not merged into the main thread. I don’t know if they all are related but it would be nice to have 1/ bug fixed, meaning that if I update an item from a background, it’s reflected in the UI, and 2/ proper documentation on how to use SwiftData with Swift Concurrency (ModelActor). I don’t know if what I’m doing in my buttons is correct or not. Thanks, Axel import SwiftData import SwiftUI @main struct FB_SwiftData_BackgroundApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: Item.self) } } } struct ContentView: View { @Environment(\.modelContext) private var modelContext @State private var simpleModelActor: SimpleModelActor! @Query private var items: [Item] var body: some View { NavigationView { VStack { if let firstItem: Item = items.first { Text(firstItem.timestamp, format: Date.FormatStyle(date: .omitted, time: .standard)) .font(.largeTitle) .fontWeight(.heavy) Button("Update from Task") { let modelContainer: ModelContainer = modelContext.container let itemID: Item.ID = firstItem.persistentModelID Task { let context: ModelContext = ModelContext(modelContainer) guard let itemInContext: Item = context.model(for: itemID) as? Item else { return } itemInContext.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000)) try context.save() } } .buttonStyle(.bordered) Button("Update from Detached Task") { let container: ModelContainer = modelContext.container let itemID: Item.ID = firstItem.persistentModelID Task.detached { let context: ModelContext = ModelContext(container) guard let itemInContext: Item = context.model(for: itemID) as? Item else { return } itemInContext.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000)) try context.save() } } .buttonStyle(.bordered) Button("Update from ModelActor") { let container: ModelContainer = modelContext.container let persistentModelID: Item.ID = firstItem.persistentModelID Task.detached { let actor: SimpleModelActor = SimpleModelActor(modelContainer: container) await actor.updateItem(identifier: persistentModelID) } } .buttonStyle(.bordered) Button("Update from ModelActor in State") { let container: ModelContainer = modelContext.container let persistentModelID: Item.ID = firstItem.persistentModelID Task.detached { let actor: SimpleModelActor = SimpleModelActor(modelContainer: container) await MainActor.run { simpleModelActor = actor } await actor.updateItem(identifier: persistentModelID) } } .buttonStyle(.bordered) Divider() .padding(.vertical) Button("Update from View") { firstItem.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000)) } .buttonStyle(.bordered) } else { ContentUnavailableView( "No Data", systemImage: "slash.circle", // 􀕧 description: Text("Tap the plus button in the toolbar") ) } } .toolbar { ToolbarItem(placement: .primaryAction) { Button(action: addItem) { Label("Add Item", systemImage: "plus") } } } } } private func addItem() { modelContext.insert(Item(timestamp: Date.now)) try? modelContext.save() } } @ModelActor final actor SimpleModelActor { var context: String = "" func updateItem(identifier: Item.ID) { guard let item = self[identifier, as: Item.self] else { return } item.timestamp = Date.now.addingTimeInterval(.random(in: 0...2000)) try! modelContext.save() } } @Model final class Item: Identifiable { var timestamp: Date init(timestamp: Date) { self.timestamp = timestamp } }
0
1
355
Oct ’24
How does one create a DataStoreSnapshot for a custom data store ?
The WWDC2024 custom data store example doesn't provide any details on how one would go about creating a DataStoreSnapshot. The example uses a DefaultSnapshot for persisting the data in the DefaultSnapshot format directly in the JSON file. There appears to be no documentation or examples of how one might create a DataStoreSnapshot from data from another database. The Apple documentation for DefaultSnapshot provides no examples of how one might create such a snapshot from data retrieved elsewhere. Can anyone provide a simple example of how one might create such a snapshot from a remote database such that it can be returned as part of the response to a fetch request. For the purpose of this example let's assume I have a CSV file with rows of data and code to read the data from this file. How would I create a snapshot or snapshots for each of the rows of data.
1
0
224
Oct ’24
Invalid bundle ID for container
I'm trying to get the CoreDataCloudKitShare example to work, but having trouble. The first error I see when running the InitializeCloudKitSchema target (on macOS) is the following: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1242): <NSCloudKitMirroringDelegate: 0x60000229c0f0>: Failed to set up CloudKit integration for store: <NSSQLCore: 0x15b807830> (URL: file:///Users/rmann/Library/Application%20Support/InitializeCloudKitSchema/CoreDataStores/Private/private.sqlite) <CKError 0x600001311290: "Partial Failure" (2/1011); "Failed to modify some record zones"; uuid = 3E1B1380-AE1C-4B14-97A8-7F60B4A8F3EF; container ID = "iCloud.com.example.CoreDataCloudKitShareH6F2W964VK"; partial errors: { com.apple.coredata.cloudkit.zone:__defaultOwner__ = <CKError 0x60000132f810: "Permission Failure" (10/2007); server message = "Invalid bundle ID for container"; op = F3987848B25CEED7; uuid = 3E1B1380-AE1C-4B14-97A8-7F60B4A8F3EF> }> I see a database in the Dashboard with that container ID, but don't know what it means by "Invalid bundle ID for container". I've seen several other posts about this across the web, and the only answer is ever "seems to be an Apple issue, wait a bit."
1
0
262
Oct ’24
SwiftData thread-safety: passing models between threads
Hello, I'm trying to understand how dangerous it is to read and/or update model properties from a thread different than the one that instantiated the model. I know this is wrong when using Core Data and we should always use perform/performAndWait before manipulating an object but I haven't found any information about that for SwiftData. Question: is it safe to pass an object from one thread (like MainActor) to another thread (in a detached Task for example) and manipulate it, or should we re fetch the object using its persistentModelID as soon as we cross threads? When running the example app below with the -com.apple.CoreData.ConcurrencyDebug 1 argument passed at launch enabled, I don't get any Console warning when I tap on the "Update directly" button. I'm sure it would trigger a warning if I were using Core Data. Thanks in advance for explaining. Axel -- @main struct SwiftDataPlaygroundApp: App { var body: some Scene { WindowGroup { ContentView() .modelContainer(for: Item.self) } } } struct ContentView: View { @Environment(\.modelContext) private var context @Query private var items: [Item] var body: some View { VStack { Button("Add") { context.insert(Item(timestamp: Date.now)) } if let firstItem = items.first { Button("Update directly") { Task.detached { // Not the main thread, but firstItem is from the main thread // No warning in Xcode firstItem.timestamp = Date.now } } Button("Update using persistentModelID") { let container: ModelContainer = context.container let itemIdentifier: Item.ID = firstItem.persistentModelID Task.detached { let backgroundContext: ModelContext = ModelContext(container) guard let itemInBackgroundThread: Item = backgroundContext.model(for: itemIdentifier) as? Item else { return } // Item on a background thread itemInBackgroundThread.timestamp = Date.now try? backgroundContext.save() } } } } } } @Model final class Item: Identifiable { var timestamp: Date init(timestamp: Date) { self.timestamp = timestamp } }
1
1
390
Oct ’24
CKContainer shareParticipant() 'missing' nameComponents
My App requires access to iCloud. I used to be able to get the User's name components (family+given name) using: let dummyZone = CKRecordZone (zoneName: UUID().uuidString) let dummyShare = CKShare (recordZoneID: dummyZone.zoneID) Persistence.logger.notice ("\(#function): Dummy 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' let userIdentity = dummyShare.owner.userIdentity where the resulting userIdentity had a filled out nameComponents. Now, recently, it seems to be empty. Did something change in the interfaces? I've also tried, more directly: let userRecordID = try await container.userRecordID() let userParticipant = try await container.shareParticipant(forUserRecordID: userRecordID) let userIdentity = userParticipant.userIdentity and still nameComponents is empty. Given that my App requires iCloud, is there a way to get (familyName,givenName)?
2
0
267
Oct ’24
ckqueryoperation in CloudKit crashing
Use CloudKit's ckqueryoperation's recordmatchedblock in Swift 6.0, which always crashes, but works fine in Swift 5: func fetchAllRecords() async throws { let predicate = NSPredicate(format: "Topics = %@", "Integrations") let query = CKQuery(recordType: "PureMList", predicate: predicate) let operation = CKQueryOperation(query: query) operation.recordMatchedBlock = { recordID, result in switch result { case .success(let record): DispatchQueue.main.async { // Ensure UI updates happen here print("Fetched record: \(record)") // Update your UI elements here } case .failure(let error): // Handle the error print("Error fetching record with ID \(recordID): \(error)") } } // Ensure you're using the correct database publicDatabase.add(operation) }
2
0
233
Oct ’24