iCloud & Data

RSS for tag

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

CloudKit Documentation

Posts under iCloud & Data subtopic

Post

Replies

Boosts

Views

Activity

macOS SwiftData app never syncs with CloudKit
I'm using SwiftData with CloutKit with a very simple app. Data syncs between iOS, iPadOS, and visionOS, but not macOS. From what I can tell, macOS is never getting CK messages unless I'm running the app from Xcode. I can listen for the CK messages and show a line in a debug overlay. This works perfectly when I run from Xcode. I can see the notifications and see updates in my app. However, if I just launch the app outside of Xcode I will never see any changes or notifications. It is as if the Mac app never even tries to contact CloudKit. Schema has been deployed in the CloudKit console. The app is based on the multi-platform Xcode template. Again, only the macOS version has this issue. Is there some extra permission or setting I need to set up in order to use CloudKit on macOS? @State private var publisher = NotificationCenter.default.publisher(for: NSPersistentCloudKitContainer.eventChangedNotification).receive(on: DispatchQueue.main) .onReceive(publisher) { notification in // Listen for changes in CK events if let userInfo = notification.userInfo, let event = userInfo[NSPersistentCloudKitContainer.eventNotificationUserInfoKey] as? NSPersistentCloudKitContainer.Event { let message = "CloudKit Sync: \(event.type.rawValue) - \(event.succeeded ? "Success" : "Failed") - \(event.description)" // Store for UI display syncNotifications.append(message) if syncNotifications.count > 10 { syncNotifications.removeFirst() } } } .overlay(alignment: .topTrailing) { if !syncNotifications.isEmpty { VStack(alignment: .leading) { ForEach(syncNotifications, id: \.self) { notification in Text(notification) .padding(8) } } .frame(width: 800, height: 500) .cornerRadius(8) .background(Color.secondary.opacity(0.2)) .padding() .transition(.move(edge: .top)) } }
1
0
127
May ’25
SwiftData 100% crash when fetching history with codable (test included!)
SwiftData crashes 100% when fetching history of a model that contains an optional codable property that's updated: SwiftData/Schema.swift:389: Fatal error: Failed to materialize a keypath for someCodableID.someID from CrashModel. It is possible that this path traverses a type that does not work with append(), please file a bug report with a test. Would really appreciate some help or even a workaround. Code: import Foundation import SwiftData import Testing struct VaultsSwiftDataKnownIssuesTests { @Test func testCodableCrashInHistoryFetch() async throws { let container = try ModelContainer( for: CrashModel.self, configurations: .init( isStoredInMemoryOnly: true ) ) let context = ModelContext(container) try SimpleHistoryChecker.hasLocalHistoryChanges(context: context) // 1: insert a new value and save let model = CrashModel() model.someCodableID = SomeCodableID(someID: "testid1") context.insert(model) try context.save() // 2: check history it's fine. try SimpleHistoryChecker.hasLocalHistoryChanges(context: context) // 3: update the inserted value before then save model.someCodableID = SomeCodableID(someID: "testid2") try context.save() // The next check will always crash on fetchHistory with this error: /* SwiftData/Schema.swift:389: Fatal error: Failed to materialize a keypath for someCodableID.someID from CrashModel. It is possible that this path traverses a type that does not work with append(), please file a bug report with a test. */ try SimpleHistoryChecker.hasLocalHistoryChanges(context: context) } } @Model final class CrashModel { // optional codable crashes. var someCodableID: SomeCodableID? // these actually work: //var someCodableID: SomeCodableID //var someCodableID: [SomeCodableID] init() {} } public struct SomeCodableID: Codable { public let someID: String } final class SimpleHistoryChecker { static func hasLocalHistoryChanges(context: ModelContext) throws { let descriptor = HistoryDescriptor<DefaultHistoryTransaction>() let history = try context.fetchHistory(descriptor) guard let last = history.last else { return } print(last) } }
0
0
62
May ’25
What xattrs does iCloud maintain?
As of 2025-05-03, when a macOS user enables iCloud Drive synchronization for Desktop &amp; Documents in US region, does iCloud filter xattrs upon upload or later when downloading back to another macOS host? Or is it the case that iCloud has no filtering of third-party xattrs? Where can I find the technical document outlining exactly what iCloud does with xattrs set on macOS host files and folders synchronized with iCloud Drive?
1
0
89
May ’25
Core Data complaining about store being opened without persistent history tracking... but I don't think that it has been
Since running on iOS 14b1, I'm getting this in my log (I have Core Data logging enabled): error: Store opened without NSPersistentHistoryTrackingKey but previously had been opened with NSPersistentHistoryTrackingKey - Forcing into Read Only mode store at 'file:///private/var/mobile/Containers/Shared/AppGroup/415B75A6-92C3-45FE-BE13-7D48D35909AF/StoreFile.sqlite' As far as I can tell, it's impossible to open my store without that key set - it's in the init() of my NSPersistentContainer subclass, before anyone calls it to load stores. Any ideas?
2
0
1.1k
May ’25
Will transferring app affect iCloud's Documents folder access?
My app uses iCloud to let users sync their files via their private iCloud Drive, which does not use CloudKit. FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appending(component: "Documents") I plan to transfer my app to another developer account, but I'm afraid it will affect the access of the app to the existing files in that folder. Apple documentation doesn't mention this case. Has anyone done this before and can confirm if the app will continue to work normally after transferring? Thanks
0
0
43
May ’25
SwiftData shared across apps?
The stuff I've found by searching has confused me, so hopefully someone can help simplify it for me? I have an app (I use it for logging which books I've given away), and I could either add a bunch of things to the app, or I could have another app (possibly a CLI tool) to generate some reports I'd like.
0
0
53
May ’25
CoreData w/ Private and Shared Configurations
I have a CoreData model with two configuration - but several problems. Notably the viewContext only shows data from the .private configuration. Here is the setup: The private configuration holds entities, for example, User and Course and the shared one holds entities, for example, Player and League. I setup the NSPersistentStoreDescriptions to use the same container but with a databaseScope of .private/.shared and with the configuration of "Private"/"Shared". loadPersistentStores() does not report an error. If I try container.initializeCloudKitSchema() only the .private configuration produces CKRecord types. If I create a companion app using one configuration (w/ all entities) the schema initialization creates all CKRecord types AND I can populate some data in the .private and a created CKShare. I see that data in the CloudKit dashboard. If I axe the companion app and run the real thing w/ two configurations, the viewContext only has the .private data. Why? If when querying history I use NSPersistentHistoryTransaction.fetchRequest I get a nil return when using two configurations (but non-nil when using one).
0
0
59
Apr ’25
Suspicious CloudKit Telemetry Data
Starting 20th March 2025, I see an increase in bandwidth and latency for one of my CloudKit projects. I'm using NSPersistentCloudKitContainer to synchronise my data. I haven't changed any CloudKit scheme during that time but shipped an update. Since then, I reverted some changes from that update, which could have led to changes in the sync behaviour. Is anyone else seeing any issues? I would love to file a DTS and use one of my credits for that, but unfortunately, I can't because I cannot reproduce it with a demo project because I cannot travel back in time and check if it also has an increase in metrics during that time. Maybe an Apple engineer can green-light me filing a DTS request, please.
0
1
96
Apr ’25
"Failed to set up CloudKit integration" in TestFlight build
I'm building a macOS + iOS SwiftUI app using Xcode 14.1b3 on a Mac running macOS 13.b11. The app uses Core Data + CloudKit. With development builds, CloudKit integration works on the Mac app and the iOS app. Existing records are fetched from iCloud, and new records are uploaded to iCloud. Everybody's happy. With TestFlight builds, the iOS app has no problems. But CloudKit integration isn't working in the Mac app at all. No existing records are fetched, no new records are uploaded. In the Console, I see this message: error: CoreData+CloudKit: Failed to set up CloudKit integration for store: <NSSQLCore: 0x1324079e0> (URL: <local file url>) Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.cloudd was invalidated: failed at lookup with error 159 - Sandbox restriction." UserInfo={NSDebugDescription=The connection to service named com.apple.cloudd was invalidated: failed at lookup with error 159 - Sandbox restriction.} I thought it might be that I was missing the com.apple.security.network.client entitlement, but adding that didn't help. Any suggestions what I might be missing? (It's my first sandboxed Mac app, so it might be really obvious to anyone but me.)
4
1
3.4k
Apr ’25
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 } }
1
1
750
Apr ’25
How to import large data from Server and save it to Swift Data
Here’s the situation: • You’re downloading a huge list of data from iCloud. • You’re saving it one by one (sequentially) into SwiftData. • You don’t want the SwiftUI view to refresh until all the data is imported. • After all the import is finished, SwiftUI should show the new data. The Problem If you insert into the same ModelContext that SwiftUI’s @Environment(.modelContext) is watching, each insert may cause SwiftUI to start reloading immediately. That will make the UI feel slow, and glitchy, because SwiftUI will keep trying to re-render while you’re still importing. How to achieve this in Swift Data ?
2
0
92
Apr ’25
Stopping certain data models from syncing to cloudkit
Hi all, I am using SwiftData and cloudkit and I am having an extremely persistent bug. I am building an education section on a app that's populated with lessons via a local JSON file. I don't need this lesson data to sync to cloudkit as the lessons are static, just need them imported into swiftdata so I've tried to use the modelcontainer like this: static func createSharedModelContainer() -> ModelContainer { // --- Define Model Groups --- let localOnlyModels: [any PersistentModel.Type] = [ Lesson.self, MiniLesson.self, Quiz.self, Question.self ] let cloudKitSyncModels: [any PersistentModel.Type] = [ User.self, DailyTip.self, UserSubscription.self, UserEducationProgress.self // User progress syncs ] However, what happens is that I still get Lesson and MiniLesson record types on cloudkit and for some reason as well, whenever I update the data models or delete and reinstall the app on simulator, the lessons duplicate (what seems to happen is that a set of lessons comes from the JSON file as it should), and then 1-2 seconds later, an older set of lessons gets synced from cloudkit. I can delete the old set of lessons if I just delete the lessons and mini lessons record types, but if I update the data model again, this error reccurrs. Sorry, I don't know if I managed to explain this well but essentially I just want to stop the lessons and minilessons from being uploaded to cloudkit as I think this will fix the problem. Am I doing something wrong with the code?
0
0
64
Apr ’25
Open child windows for a document in a document based SwiftData app
In a document based SwiftData app for macOS, how do you go about opening a (modal) child window connected to the ModelContainer of the currently open document? Using .sheet() does not really result in a good UX, as the appearing view lacks the standard window toolbar. Using a separate WindowGroup with an argument would achieve the desired UX. However, as WindowGroup arguments need to be Hashable and Codable, there is no way to pass a ModelContainer or a ModelContext there: WindowGroup(id: "myWindowGroup", for: MyWindowGroupArguments.self) { $args in ViewThatOpensInAWindow(args: args) } Is there any other way?
0
0
31
Apr ’25
CKSyncEngine save existing CKRecord
I have transitioned to CKSyncEngine for syncing data to iCloud, and it is working quite well. I have a question regarding best practices for modifying and saving a CKRecord which already exists in the private or shared database. In my current app, most CKRecords will never be modified after saving to the database, so I do not persist a received record locally after updating my local data model. In the rare event that the local data for that record is modified, I manually fetch the associated server record from the database, modify it, and then use CKSyncEngine to save the modified record. As an alternative method, I can create a new CKRecord locally with the corresponding recordID and the modified data, and then use CKSyncEngine to attempt to save that record to the database. Doing so generates an error in the delegate method handleSentRecordZoneChanges, where I receive the local record I tried to save back inevent.failedRecordSaves with a .serverRecordChanged error, along with the corresponding server CKRecord. I can then update that server record with the local data and re-save using CKSyncEngine. I have not yet seen any issues when doing it this way. The advantage of the latter method is that CKSyncEngine handles the entire database operation, eliminating the manual fetch step. My question is: is this an acceptable practice, or could this result in other unforeseen issues?
2
0
72
Apr ’25
Is it possible to use an additional local ModelContainer in a document based SwiftData app?
I have a document based SwiftData app in which I would like to implement a persistent cache. For obvious reasons, I would not like to store the contents of the cache in the documents themselves, but in my app's data directory. Is a use case, in which a document based SwiftData app uses not only the ModelContainers from the currently open files, but also a ModelContainer writing a database file in the app's documents directory (for cache, settings, etc.) supported? If yes, how can you inject two different ModelContexts, one tied to the currently open file and one tied to the local database, into a SwiftUI view?
0
0
45
Apr ’25
Core Data and Swift 6 concurrency: returning an NSManagedObject
We're in the process of migrating our app to the Swift 6 language mode. I have hit a road block that I cannot wrap my head around, and it concerns Core Data and how we work with NSManagedObject instances. Greatly simplied, our Core Data stack looks like this: class CoreDataStack { private let persistentContainer: NSPersistentContainer var viewContext: NSManagedObjectContext { persistentContainer.viewContext } } For accessing the database, we provide Controller classes such as e.g. class PersonController { private let coreDataStack: CoreDataStack func fetchPerson(byName name: String) async throws -> Person? { try await coreDataStack.viewContext.perform { let fetchRequest = NSFetchRequest<Person>() fetchRequest.predicate = NSPredicate(format: "name == %@", name) return try fetchRequest.execute().first } } } Our view controllers use such controllers to fetch objects and populate their UI with it: class MyViewController: UIViewController { private let chatController: PersonController private let ageLabel: UILabel func populateAgeLabel(name: String) { Task { let person = try? await chatController.fetchPerson(byName: name) ageLabel.text = "\(person?.age ?? 0)" } } } This works very well, and there are no concurrency problems since the managed objects are fetched from the view context and accessed only in the main thread. When turning on Swift 6 language mode, however, the compiler complains about the line calling the controller method: Non-sendable result type 'Person?' cannot be sent from nonisolated context in call to instance method 'fetchPerson(byName:)' Ok, fair enough, NSManagedObject is not Sendable. No biggie, just add @MainActor to the controller method, so it can be called from view controllers which are also main actor. However, now the compiler shows the same error at the controller method calling viewContext.perform: Non-sendable result type 'Person?' cannot be sent from nonisolated context in call to instance method 'perform(schedule:_:)' And now I'm stumped. Does this mean NSManageObject instances cannot even be returned from calls to NSManagedObjectContext.perform? Ever? Even though in this case, @MainActor matches the context's actor isolation (since it's the view context)? Of course, in this simple example the controller method could just return the age directly, and more complex scenarios could return Sendable data structures that are instantiated inside the perform closure. But is that really the only legal solution? That would mean a huge refactoring challenge for our app, since we use NSManageObject instances fetched from the view context everywhere. That's what the view context is for, right? tl;dr: is it possible to return NSManagedObject instances fetched from the view context with Swift 6 strict concurrency enabled, and if so how?
0
0
70
Apr ’25
Core Data transformable attribute problem in Xcode16
Hi everyone, Have anybody faced with Core Data issues, trying to migrate the project to Xcode16 beta 4? We are using transformableAttributeType in some entities, with attributeValueClassName = "[String]" and valueTransformerName = "NSSecureUnarchiveFromData". It is working just fine for years, but now I am trying to run the project from Xcode16 and have 2 issues: in Xcode logs I see warning and error: CoreData: fault: Declared Objective-C type "[String]" for attribute named alertBarChannels is not valid CoreData: Declared Objective-C type "[String]" for attribute named alertBarChannels is not valid periodically the app crashes when we are assigning value to this attribute, with error: Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFConstantString characterAtIndex:]: Range or index out of bounds' Once again, in Xcode 15 it works fine, and it was working for years. Cannot find any information about what was changed in the framework... Thank you in advance for any information, which could clarify what is going on.
15
14
4.1k
Apr ’25