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

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.
3
0
155
1d
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.
1
0
91
20h
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
160
4d
Mapping model not found if the attribute has "Preserve after deletion" enabled
I am trying to migrate my Core Data model to a new version with a new attribute added to it. Since my app supports macOS 13 I am not able to use the newly introduced Staged migrations. After much digging I found that the app is not able to find the Mapping Model when one of the attribute has "Preserve after deletion" enabled. I have enabled migration debbuging using com.apple.CoreData.MigrationDebug 1 I am getting following error error: CoreData: error: (migration) migration failed with error Error Domain=NSCocoaErrorDomain Code=134140 "Persistent store migration failed, missing mapping model." What is the way out here?
6
0
367
2w
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: &lt;CKError 0x3018ac3c0: "Internal Error" (1/3001); "MMCSEngineCreate failed"&gt; 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 &lt;CKError 0x3018ac1e0: "Internal Error" (1/3001); "MMCSEngineCreate failed"&gt;
0
0
229
3d
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
129
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
78
2d
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
167
2d
Document-based SwiftData apps fail to identify a store on iPad?
When trying to run my document-based iPad app using iPadOS 18 beta and Xcode 16 beta, I get an error like the following after opening a document: Thread 1: Fatal error: Failed to identify a store that can hold instances of SwiftData._KKMDBackingData<MyProject.MyModel> from [:] In order to help track down what is going wrong, I downloaded the sample app from WWDC23 session "Build an app with SwiftData" found here: https://developer.apple.com/documentation/swiftui/building-a-document-based-app-using-swiftdata When I try to run the end-state of that sample code, I get a similar error when running the app on my iPad and creating a new deck: Thread 1: Fatal error: Failed to identify a store that can hold instances of SwiftData._KKMDBackingData<SwiftDataFlashCardSample.Card> from [:] Given that the sample project is generating the same error as my own project, is this a problem with SwiftData and document-based apps in general? Or is there a change of approach that I should try?
17
10
2.1k
Jun ’24
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
213
5d
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
365
1w
Documents folder of my app not shown in iCloud Drive in Finder
The problem is that the iCloud Drive directory of my app does not appear in my iCloud Drive in Finder despite the (I think) correct settings in my info.plist file (see below). In Terminal, I can see the folder and it also contains .txt files. What can I do to make the folder visible in Finder and the Files app? <key>NSUbiquitousContainers</key> <dict> <key>iCloud.vmk.NewsSwiper</key> <dict> <key>NSUbiquitousContainerIsDocumentScopePublic</key> <true/> <key>NSUbiquitousContainerName</key> <string>RSS-Filter</string> <key>NSUbiquitousContainerIdentifier</key> <string>iCloud.vmk.NewsSwiper</string> <key>NSUbiquitousContainerSupportedFolderLevels</key> <string>Any</string> </dict> </dict>
3
0
322
2w
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
304
1w
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
257
1w
modelContext.fetch() hits assert on release builds, but not on debug builds
Exact same app works fine in debug builds, but on release builds I see this stacktrace indicating that assert() was hit. Incident Identifier: *** Distributor ID: com.apple.TestFlight Hardware Model: iPhone14,3 Process: AuditOS [67847] Path: /private/var/containers/Bundle/Application/*** Identifier: *** Version: 1.0 (15) AppStoreTools: 16C5031b AppVariant: 1:iPhone14,3:18 Beta: YES Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: *** Date/Time: 2025-02-11 12:37:54.7801 -0600 Launch Time: 2025-02-11 12:37:33.1737 -0600 OS Version: iPhone OS 18.3 (22D63) Release Type: User Baseband Version: 4.20.03 Report Version: 104 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x000000019d388e2c Termination Reason: SIGNAL 5 Trace/BPT trap: 5 Terminating Process: exc handler [67847] Triggered by Thread: 0 Thread 0 Crashed: 0 libswiftCore.dylib 0x000000019d388e2c _assertionFailure(_:_:file:line:flags:) + 264 (AssertCommon.swift:147) 1 SwiftData 0x0000000261842e04 Schema.KeyPathCache.validateAndCache(keypath:on:) + 2628 (Schema.swift:0) 2 SwiftData 0x000000026178cac4 static PersistentModel.keyPathToString(keypath:) + 360 (DataUtilities.swift:36) 3 SwiftData 0x000000026184c9e4 static PersistentModel.fetchDescriptorKeyPathString(for:) + 36 (FetchDescriptor.swift:51) 4 SwiftData 0x00000002617b9770 closure #1 in PredicateExpressions.KeyPath.convert(state:) + 172 (FetchDescriptor.swift:458) 5 SwiftData 0x00000002617b7f48 PredicateExpressions.KeyPath.convert(state:) + 352 (FetchDescriptor.swift:438) 6 SwiftData 0x00000002617bb7ec protocol witness for ConvertibleExpression.convert(state:) in conformance PredicateExpressions.KeyPath&lt;A, B&gt; + 16 (&lt;compiler-generated&gt;:0) 7 SwiftData 0x00000002617baaa0 PredicateExpression.convertToExpressionOrPredicate(state:) + 716 (FetchDescriptor.swift:219) 8 SwiftData 0x00000002617ba6dc PredicateExpression.convertToExpression(state:) + 32 (FetchDescriptor.swift:237) 9 SwiftData 0x00000002617b7cfc PredicateExpressions.Equal.convert(state:) + 328 (:-1) 10 SwiftData 0x00000002617bba08 protocol witness for ConvertibleExpression.convert(state:) in conformance PredicateExpressions.Equal&lt;A, B&gt; + 64 (&lt;compiler-generated&gt;:0) 11 SwiftData 0x00000002617baaa0 PredicateExpression.convertToExpressionOrPredicate(state:) + 716 (FetchDescriptor.swift:219) 12 SwiftData 0x00000002617b7abc PredicateExpression.convertToPredicate(state:) + 28 (FetchDescriptor.swift:244) 13 SwiftData 0x00000002617b7190 nsFetchRequest&lt;A&gt;(for:in:) + 1204 (FetchDescriptor.swift:64) 14 SwiftData 0x0000000261783358 DefaultStore.fetch&lt;A&gt;(_:) + 292 (DefaultStore.swift:496) 15 SwiftData 0x000000026178322c protocol witness for DataStore.fetch&lt;A&gt;(_:) in conformance DefaultStore + 16 (&lt;compiler-generated&gt;:0) 16 SwiftData 0x00000002617847fc asDataStore #1 &lt;A&gt;&lt;A1&gt;(_:) in closure #1 in ModelContext.fetch&lt;A&gt;(_:) + 3152 (ModelContext.swift:2590) 17 SwiftData 0x00000002617a74d8 partial apply for closure #1 in ModelContext.fetch&lt;A&gt;(_:) + 100 (&lt;compiler-generated&gt;:0) 18 SwiftData 0x00000002617a7438 closure #1 in ModelContext.enumerateFetchableStores&lt;A&gt;(_:_:) + 208 (ModelContext.swift:2527) 19 SwiftData 0x00000002617a731c specialized ModelContext.enumerateFetchableStores&lt;A&gt;(_:_:) + 200 (ModelContext.swift:2522) 20 SwiftData 0x00000002617a6f08 ModelContext.fetch&lt;A&gt;(_:) + 144 (ModelContext.swift:2534) 21 SwiftData 0x00000002617a6e70 dispatch thunk of ModelContext.fetch&lt;A&gt;(_:) + 56 (:-1) 22 AuditOS 0x00000001041af3f4 0x10419c000 + 78836 23 AuditOS 0x00000001041bebd5 0x10419c000 + 142293 24 AuditOS 0x00000001041bbbf5 0x10419c000 + 130037 25 AuditOS 0x00000001041d8be5 0x10419c000 + 248805 26 AuditOS 0x00000001041bde6d 0x10419c000 + 138861 27 libswift_Concurrency.dylib 0x00000001aa6bfe39 completeTaskWithClosure(swift::AsyncContext*, swift::SwiftError*) + 1 (Task.cpp:497) The code in question looks like this: func addRecord&lt;T: MyDtoProtocol&gt;(_ someDTO: T) async throws { var zone: ZoneModel? = nil let recordName = someDTO.recordNameType let fetchDescriptor = FetchDescriptor&lt;T.ModelType&gt; (predicate: #Predicate {$0.recordName == recordName}) &gt; var localEntitites: [T.ModelType] = try modelContext.fetch(fetchDescriptor) &lt;---- I have isolated crash to this line. Basically for each swiftdata model type I have associatedType for Data Transfer Object type and vice versa.
4
1
377
2w
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
278
1w