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

Cloudkit not synching across devices after latest ios update
After a recent iOS update, my app is not synching between devices. I'm not seeing or getting any errors. CLoudKit Logs show activity, but it's not happening realtime. Even if I close and reopen the app, it won't sync between devices. It almost looks like it only has local storage now and CloudKit is not working on it anymore. STEPS TO REPRODUCE Use app on two devices with the same Apple ID. Create a user and one device and it won't show up on the other device. Vice Versa.
0
0
63
7h
Int128 fail in @Model with SwiftData
Swift recently added support for Int128. However, they do need NOT seem to be supported in SwiftData. Now totally possible I'm doing something wrong too. I have the project set to macOS 15 to use a UInt128 in @Model class as attribute. I tried using a clean Xcode project with Swift Data choosen in the macOS app wizard. Everything compiles, but it fails at runtime in both my app and "Xcode default" SwiftData: SwiftData/SchemaProperty.swift:380: Fatal error: Unexpected property within Persisted Struct/Enum: Builtin.Int128 with the only modification to from stock is: @Model final class Item { var timestamp: Date var ipv6: UInt128 init(timestamp: Date) { self.timestamp = timestamp self.ipv6 = 0 } } I have tried both Int128 and UInt128. Both fails exactly the same. In fact, so exactly, when using UInt128 it still show a "Int128" in error message, despite class member being UInt128 . My underlying need is to store an IPv6 addresses with an app, so the newer UInt128 would work to persist it. Since Network Framework IPv6Address is also not compatible, it seems, with SwiftData. So not a lot of good options, other an a String. But for an IPv6 address that suffers from that same address can take a few String forms (i.e. "0000:0000:0000:0000:0000:0000:0000:0000" =="0:0:0:0:0:0:0:0" == "::") which is more annoying than having a few expand Int128 as String separator ":". Ideas welcomed. But potentially a bug in SwiftData since Int128 is both a Builtin and conforms to Codable, so from my reading it should work.
2
0
132
1d
Async Data with iCloud
DESCRIPTION I have an App use iCloud to save data. The App had a CoreData ManagedObject 'Product', 'Product' Object had an attribute name 'count' and it is a Double Type. I need to synchronises 'count' property across multiple devices. for example: I have a devices A、B. A device set 'Product.count' = 100. B device set 'Product.count' = 50. I hope the 'Product.count' == 150 that results. how to synchronises the 'Product.count' == 150 for multiple devices. If I have more devices in future, How to get the latest 'Product.count' that it is correct result.
0
0
127
1d
Records or Fields are Missing or Corrupt in Users Private CloudKit Databases (Recent Changes to CloudKit?)
Hi all, I've contacted Apple about this privately but I wanted to post this publicly too just to see if anyone else is experiencing the same issue. We use CloudKit to store "documents" (we'll call them) for our users. We use it directly, not via CoreData etc but through the lower level APIs. This has been working great for the last 9 months or so. Since a few days ago we've started receiving reports from users that their data has disappeared without a trace from their app. Obviously this is very serious and severe for us. We keep a local copy of the users data but if CloudKit tells us this data has been deleted we remove that local copy to keep in sync. Nothing has changed client side in terms of our code, and the only way we can see that could cause this, is a fetch that we perform asking for a list of the users "documents" is returning no rows/results, or possibly returning rows with invalid or missing fields. We have about 30,000 active users per day (1.5m requests/day) using CloudKit and we have only a handful of reports of this. Again this only started happening this week after 9 months of good service. Has anyone else noticed anything "strange" lately, fetches returning empty? fields missing? Is anyone at Apple aware of any recent changes to CloudKit? or outages? We're really unsure how or who should handle this and who we can escalate to? Any help appreciated. We have a workaround/mitigation on the way through review at the moment but this is a really big problem for us if we can't rely on CloudKit to remember users data reliably.
0
0
164
2d
SwiftData migration error: NSCloudKitMirroringDelegate are not reusable
Hello everyone, I used SwiftData for v1 of an app and am now trying to make changes to the schema for v2. I created the v2 schema that adds a property to one of the models. I need to populate the new property so I made a custom migration using didMigrate. However that doesn't seem to matter what I do in the migration because creating the ModelContainer throws an error before didMigrate ever gets called. The error is: Unresolved error loading container Error Domain=NSCocoaErrorDomain Code=134060 "A Core Data error occurred." UserInfo={NSLocalizedFailureReason=Instances of NSCloudKitMirroringDelegate are not reusable and should have a lifecycle tied to a given instance of NSPersistentStore.} Higher up in the Xcode output I see things like this (in order): Request 'D25A8CB8-7341-4FA8-B2F8-3DE2D35B5273' was cancelled because the store was removed from the coordinator. BUG IN CLIENT OF CLOUDKIT: Registering a handler for a CKScheduler activity identifier that has already been registered 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. How can I know from this output what I am doing incorrectly? Any idea what I should take a look at or try to do differently? This is a simple app with three models and nothing fancy. The only change in the schema is to add a property. The new property is declared as optional and has an inverse that is also declared as optional. Thanks for any insight!
1
0
75
2d
CloudKit CKModifyRecordsOperation resulting in undocumented error "Internal Error" (1/3001); "MMCSEngineCreate failed"
I'm running into an undocumented error coming back from CloudKit operations. Specifically, I'm attempting to save new records via CKModifyRecordsOperation. I'm receiving this error for each of the records in the perRecordSaveBlock callback: <CKError 0x3018ac3c0: "Internal Error" (1/3001); "MMCSEngineCreate failed"> Is anyone else facing this error? It has been happening for several days and I'm finally getting around to reproduction with the Console app and logs. I have 16 records on my device locally that each one gets this error back. FB16547732 - CloudKit: CKModifyRecordsOperation saving new records results in Error <CKError 0x3018ac1e0: "Internal Error" (1/3001); "MMCSEngineCreate failed">
0
0
226
3d
Crashes when trying to destroy persistent store
I am running into some issues when trying to destroy CoreData persistentStores. When a user logs out of my app, I want to completely reset CoreData and delete any existing data. My code to reset CoreData looks like this: let coordinator = self.persistentContainer.persistentStoreCoordinator self.persistentContainer.viewContext.reset() coordinator.persistentStores.forEach { store in guard let url = store.url else { return } do { try coordinator.destroyPersistentStore(at: url, type: .sqlite) _ = try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url) } catch { print(error) } } However, my app is crashing with Object 0xb2b5cc80445813de <x-coredata://BDB999D4-49A4-4CB3-AC3A-666AD60BEFC6/AccountEntity/p5> persistent store is not reachable from this NSManagedObjectContext's coordinator It seems this is related to the SwiftUI @FetchRequest wrappers. If I do not open the views where I am using @FetchRequest, the logout goes smoothly. Otherwise, I get the crash above. Has anyone run into anything similar? Is there something else I need to do to get the underlying FRC to release its references to those entities? I was under the impression that calling reset() on the managed object context would be enough to remove those items from memory and get the destroying of the persistent store to go smoothly. Alternately, is there another/better way I should be destroying the DB? Any advice or related observations would be greatly appreciated. Thank you!
2
0
147
3d
Proper way to use a ModelContext from a background thread in a document based app
What is the idiomatic way to use a ModelContext in a document based SwiftData app from a background thread? The relevant DocumentGroup initializers do not give us direct access to a ModelContainer, only to a ModelContext. Is it safe to take its modelContext.container and pass it around (for creating a ModelContext on it on a background thread) or to construct a ModelActor with it? Is it safe to e.g. put a ModelActor so created into the environment of the root view of the window and execute various async data operations on it in Tasks throughout the app, as long as these are dispatched from within the window whose root view's ModelContext was used for getting the ModelContainer?
1
1
202
4d
Core Data Light Migration Crash When Widget is Installed (Error 134100)
I'm experiencing a crash during a lightweight Core Data migration when a widget that accesses the same database is installed. The migration fails with the following error: CoreData: error: addPersistentStoreWithType:configuration:URL:options:error: returned error NSCocoaErrorDomain (134100) error: userInfo: CoreData: error: userInfo: error: metadata : { NSPersistenceFrameworkVersion = 1414; NSStoreModelVersionChecksumKey = "dY78fBnnOm7gYtb+QT14GVGuEmVlvFSYrb9lWAOMCTs="; NSStoreModelVersionHashes = { Entity1 = { ... }; Entity2 = { ... }; Entity3 = { ... }; Entity4 = { ... }; Entity5 = { ... }; }; NSStoreModelVersionHashesDigest = "aOalpc6zSzr/VpduXuWLT8MLQFxSY4kHlBo/nuX0TVQ/EZ+MJ8ye76KYeSfmZStM38VkyeyiIPf4XHQTMZiH5g=="; NSStoreModelVersionHashesVersion = 3; NSStoreModelVersionIdentifiers = ( "" ); NSStoreType = SQLite; NSStoreUUID = "9AAA7AB7-18D4-4DE4-9B54-893D08FA7FC4"; "_NSAutoVacuumLevel" = 2; } The issue occurs only when the widget is installed. If I remove the widget’s access to the Core Data store, the migration completes successfully. The crash happens only once—after the app is restarted, everything works fine. This occurs even though I'm using lightweight migration, which should not require manual intervention. My suspicion is that simultaneous access to the Core Data store by both the main app and the widget during migration might be causing the issue. Has anyone encountered a similar issue? Is there a recommended way to ensure safe migration while still allowing the widget to access Core Data? Any insights or recommendations would be greatly appreciated.
3
0
243
1w
Any SwiftData change updates every SwiftUI view
Perhaps I just have the wrong expectations, but I discovered some odd behavior from SwiftData that sure seems like a bug to me... If you make any change to any SwiftData model object — even just setting a property to its current value — every SwiftUI view that uses SwiftData is rebuilt. Every query and every entity reference, even if the property was set on a model class that is completely unrelated to the view. SwiftUI does such a good job of optimizing UI updates that it's hard to notice the issue. I only noticed it because the updates were triggering my debug print statements. To double-check this, I went back to Apple's new iOS app template — the one that is just a list of dated items — and added a little code to touch an unrelated record in the background: @Model class UnrelatedItem { var name: String init(name: String) { self.name = name } } @main struct jumpyApp: App { var sharedModelContainer: ModelContainer = { let schema = Schema([ Item.self, UnrelatedItem.self ]) let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) do { return try ModelContainer(for: schema, configurations: [modelConfiguration]) } catch { fatalError("Could not create ModelContainer: \(error)") } }() init() { let context = sharedModelContainer.mainContext // Create 3 items at launch so we immediately have some data to work with. if try! context.fetchCount(FetchDescriptor<Item>()) == 0 { for _ in 0..<3 { let item = Item(timestamp: Date()) context.insert(item) } } // Now create one unrelated item. let unrelatedItem = UnrelatedItem(name: "Mongoose") context.insert(unrelatedItem) try? context.save() // Set up a background task that updates the unrelated item every second. Task { while true { try? await Task.sleep(nanoseconds: 1_000_000_000) Task { @MainActor in // We don't even have to change the name or save the contxt. // Just setting the name to the same value will trigger a change. unrelatedItem.name = "Mongoose" } } } } var body: some Scene { WindowGroup { ContentView() } .modelContainer(sharedModelContainer) } } I also added a print statement to the ContentView so I could see when the view updates. struct ContentView: View { @Environment(\.modelContext) private var modelContext @Query private var items: [Item] var body: some View { NavigationSplitView { List { let _ = Self._printChanges() ... The result is that the print statement logs 2 messages to the debug console every second. I checked in iOS 17, 18.1, and 18.2, and they all behave this way. Is this the intended behavior? I thought the whole point of the new Observation framework in iOS 17 was to track which data had changed and only send change notifications to observers who were using that data.
2
0
347
1w
Fetching strategies - Do not fetch redundant data. ETags, Lastmodified, own API? Recommendations, practice?
I am developing an Xcode app with a job feed, with profile view, with chat eg. I fetch using federatet queries to my microservices thru Apollo Router. Infront of the Apollo Router i Have a Kong that adds a X user ID, that the microservices use for personalized feed and other user info. The info is stored with SwiftData. My thought is that i should add a better way of controlling when i need to fetch. I have a “lastupdateAPI” with different entities (profile, profile picture eg). So when nothing has changed we do not fetch. But rather then using a own API for this, isnt ETag better? Or is it any other recommendations with Xcode Swiftui. Good strategies for not fetching what i already have?
2
0
266
1w
Document based SwiftData apps do not autosave
Document based SwiftData apps do not autosave changes to the ModelContext at all. This issue has been around since the first release of this SwiftData feature. In fact, the Apple WWDC sample project (https://developer.apple.com/documentation/swiftui/building-a-document-based-app-using-swiftdata) does not persist any data in its current state, unless one inserts modelContext.save() calls after every data change. I have reported this under the feedback ID FB16503154, as it seemed to me that there is no feedback report about the fundamental issue yet. Other posts related to this problem: https://forums.developer.apple.com/forums/thread/757172 https://forums.developer.apple.com/forums/thread/768906 https://developer.apple.com/forums/thread/764189
0
0
157
1w
NSPersistentCloudKitContainer uploads only a subset of records to public database in production environment
I'm having some issues where only a subset of records appear in CloudKit dashboard after I have saved some records in my iOS app using NSPersistentCloudKitContainer. I have noticed that when I'm running my app using the development environment of my CloudKit container everything works smoothly and is uploaded as expected but when I'm using the production environment only a subset of records are actually uploaded. I'm pulling my hair on how to debug this. -com.apple.CoreData.CloudKitDebug and -com.apple.CoreData.SQLDebug pukes out too much info in the console for me to pinpoint any issue.
1
0
283
1w
SwiftData property marked ephemeral getting persisted in CloudKit
Am I misunderstanding the expected behavior here, or is there a bug in the behavior of @Attribute(.ephemeral) tagged SwiftData model properties? The documentation for .ephemeral says "Track changes to this property but do not persist". I started using .ephemeral because @Transient was inhibiting SwiftUI from reacting to changes to the property through @Observable. I am updating the value of my @Attribute(.ephemeral) property about once a second and I am seeing corresponding console log output showing the property as part of the generated CKRecord object. I then confirmed in the CloudKit dev portal that the .ephemeral property was added to the Record schema and contains real values. The behavior seems as though the .ephemeral property is being completely ignored. This is observed in a new Xcode project using SwiftData with CloudKit, Xcode 16.2, macOS 15.3.1 and during Build & Run testing on physical devices.
1
0
267
1w
SwiftData One To Many
I'm working through the Develop In Swift tutorial at page [https://developer.apple.com/tutorials/develop-in-swift/navigation-editing-and-relationships-conclusion)] The tutorial has a one to many relationship between Friend and Movie (each friend can have at most one favorite movie and each movie can be the favorite for zero or more friends). An exercise left to the student is to use an .onDelete on the movie detail page to delete that movie as favorite. I modified the Form Form { TextField("Movie title", text: $movie.title) DatePicker("Release date", selection: $movie.releaseDate, displayedComponents: .date) if !movie.favoritedBy.isEmpty { Section("Favorited by") { ForEach(sortedFriends) { friend in Text(friend.name) } .onDelete(perform: deleteFavorites(indexes:)) } } } by adding the .onDelete clause I added private func deleteFavorites(indexes: IndexSet) { for index in indexes { context.delete(movie.favoritedBy[index]) } } to the view. This does delete the favorite movie, but it also deletes the friend. My assumption is that the selected friend should then have no favorite movie rather than being deleted There is an if in the Form that doesn't display the FAVORITED BY section if no friend has that movie as a favorite, but if I delete all the friends who had this movie as a favorite, the section remains (but is empty), until I exit the MovieDetail view and reload it There is no answer for these exercises, so I could be doing it wrong. EDIT: If I delete a movie using the app function to delete a movie, friends that have that movie as a favorite are not deleted and have their favorite movie set to None
3
0
322
1w
Nested method calls in `context.perform` with Swift 6
I'm calling a method with the context as parameter, within the context's perform block – is this really not legal in Swift 6? actor MyActor { func bar(context: NSManagedObjectContext) { /* some code */ } func foo(context: NSManagedObjectContext) { context.performAndWait { self.bar(context: context) // WARN: Sending 'context' risks causing data races; this is an error in the Swift 6 language mode // 'self'-isolated 'context' is captured by a actor-isolated closure. actor-isolated uses in closure may race against later nonisolated uses // Access can happen concurrently } } } The warning appears when I call a method with a context parameter, within the performAndWait-block. Background: In my app I have methods that takes in API data, and I need to call the same methods from multiple places with the same context to store it, and I do not want to copy paste the code and have hundreds of lines of duplicate code. Is there a well-known "this is how you should do it" for situations like this? This is related to a previous post I made, but it's a bit flimsy and got no response: https://developer.apple.com/forums/thread/770605
1
1
303
1w
What is CloudKit error: AssetUploadTokenRetrieveRequest request size exceeds limit
Some of my customer get the following CloudKit error (I cannot reproduce is myself). Failed to modify some records (CKErrorDomain:2) userInfo: CKErrorDescription:Failed to modify some records CKPartialErrors:{ "<CKRecordID: ooo; recordName=ooo, zoneID=ooo:__defaultOwner__>" = "<CKError 0x600003809ce0: \"Limit Exceeded\" (27/2023); server message = \"AssetUploadTokenRetrieveRequest request size exceeds limit\"; op = ooo; uuid = ooo; container ID = \"ooo\">" This is a CKError.limitExeeded error. I create 200 or less records in a batch operation. So I am below the 400 limit. Searching the Internet for "AssetUploadTokenRetrieveRequest request size exceeds limit": 0 results Can anyone give me a hint?
4
0
291
1w