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">
iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
Post
Replies
Boosts
Views
Activity
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!
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?
I haven't been able to find a definitive answer to this online. Is NSUbiquitousKeyValueStore end-to-end encrypted with Advanced Data Protection turned on? It’s not specifically called out here https://support.apple.com/en-us/102651.
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.
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.
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?
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
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.
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.
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
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
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?
Hello,
I am trying to access my cloudkit database from the icloud developer dashboard but I am getting the following error:
Error looking up Developer Teams
XHR request failure
Please sign out and try again.
I tried signing out but the error persists,
Thanks
I am trying to test using Testflight and have set up a test with a user on an account I also own which is different to me developer account. The app I believe is running in production on a separate device and is working from a user point of view, however I am not able to query the data via the console. As I said I know the user id and password as tey are mine so even when I use the Act as user service it logs in but the query is empty. I'm assuming I'm not doing anything wrong its possibly an security issue that is preventing me accessing this account. My question to the group then is how do I verify the data that is being tested?
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<A, B> + 16 (<compiler-generated>: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<A, B> + 64 (<compiler-generated>: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<A>(for:in:) + 1204 (FetchDescriptor.swift:64)
14 SwiftData 0x0000000261783358 DefaultStore.fetch<A>(_:) + 292 (DefaultStore.swift:496)
15 SwiftData 0x000000026178322c protocol witness for DataStore.fetch<A>(_:) in conformance DefaultStore + 16 (<compiler-generated>:0)
16 SwiftData 0x00000002617847fc asDataStore #1 <A><A1>(_:) in closure #1 in ModelContext.fetch<A>(_:) + 3152 (ModelContext.swift:2590)
17 SwiftData 0x00000002617a74d8 partial apply for closure #1 in ModelContext.fetch<A>(_:) + 100 (<compiler-generated>:0)
18 SwiftData 0x00000002617a7438 closure #1 in ModelContext.enumerateFetchableStores<A>(_:_:) + 208 (ModelContext.swift:2527)
19 SwiftData 0x00000002617a731c specialized ModelContext.enumerateFetchableStores<A>(_:_:) + 200 (ModelContext.swift:2522)
20 SwiftData 0x00000002617a6f08 ModelContext.fetch<A>(_:) + 144 (ModelContext.swift:2534)
21 SwiftData 0x00000002617a6e70 dispatch thunk of ModelContext.fetch<A>(_:) + 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<T: MyDtoProtocol>(_ someDTO: T) async throws {
var zone: ZoneModel? = nil
let recordName = someDTO.recordNameType
let fetchDescriptor = FetchDescriptor<T.ModelType> (predicate: #Predicate {$0.recordName == recordName})
> var localEntitites: [T.ModelType] = try modelContext.fetch(fetchDescriptor) <---- I have isolated crash to this line.
Basically for each swiftdata model type I have associatedType for Data Transfer Object type and vice versa.
When I try to promote schema to production, I get following error:
Cannot promote schema with empty type 'workspace', please delete the record type before attempting to migrate the schema again
However, in hierarchical root record sharing, I think it should be completely legit use case where there is empty root record (in my case workspace) to which other records reference through ->parent reference.
Am I missing something? Is this weird constraint imposed on CloudKit?
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?
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>
I'm unable to view Changes or Diff View in the Deploy Schema Changes Dialog due to an Internal Error.