Hi everyone,
I’ve been working on migrating my app (SwimTimes, which helps swimmers track their times) to use Core Data + CKSyncEngine with Swift 6.
After many iterations, forum searches, and experimentation, I’ve created a focused sample project that demonstrates the architecture I’m using.
The good news:
👉 I believe the crashes I was experiencing are now solved, and the sync behavior is working correctly.
👉 The demo project compiles and runs cleanly with Swift 6.
However, before adopting this as the final architecture, I’d like to ask the community (and hopefully Apple engineers) to validate a few critical points, especially regarding Swift 6 concurrency and Core Data contexts.
Architecture Overview
Persistence layer: Persistence.swift sets up the Core Data stack with a main viewContext and a background context for CKSyncEngine.
Repositories: All Core Data access is abstracted into repository classes (UsersRepository, SwimTimesRepository), with async/await methods.
SyncEngine: Wraps CKSyncEngine, handles system fields, sync tokens, and bridging between Core Data entities and CloudKit records.
ViewModels: Marked @MainActor, exposing @Published arrays for SwiftUI. They never touch Core Data directly, only via repositories.
UI: Simple SwiftUI views bound to the ViewModels.
Entities:
UserEntity → represents swimmers.
SwimTimeEntity → times linked to a user (1-to-many).
Current Status
The project works and syncs across devices. But there are two open concerns I’d like validated:
Concurrency & Memory Safety
Am I correctly separating viewContext (main/UI) vs. background context (used by CKSyncEngine)?
Could there still be hidden risks of race conditions or memory crashes that I’m not catching?
Swift 6 Sendable Compliance
Currently, I still need @unchecked Sendable in the SyncEngine and repository layers.
What is the recommended way to fully remove these workarounds and make the code safe under Swift 6’s stricter concurrency rules?
Request
Please review this sample project and confirm whether the concurrency model is correct.
Suggest how I can remove the @unchecked Sendable annotations safely.
Any additional code improvements or best practices would also be very welcome — the intention is to share this as a community resource.
I believe once finalized, this could serve as a good reference demo for Core Data + CKSyncEngine + Swift 6, helping others migrate safely.
Environment
iOS 18.5
Xcode 16.4
macOS 15.6
Swift 6
Sample Project
Here is the full sample project on GitHub:
👉 [https://github.com/jarnaez728/coredata-cksyncengine-swift6]
Thanks a lot for your time and for any insights!
Best regards,
Javier Arnáez de Pedro
iCloud & Data
RSS for tagLearn how to integrate your app with iCloud and data frameworks for effective data storage
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I have a simple app that makes an HTTPS call to gather some JSON which I then parse and add to my SwiftData database. The app then uses a simple @Query in a view to get the data into a list.
on iOS 16 this works fine. No problems. But the same code on iOS 26 (targeting iOS 18.5) crashes after about 15 seconds of idle time after the list is populated. The error message is:
Could not cast value of type '__NSCFNumber' (0x1f31ee568) to 'NSString' (0x1f31ec718).
and occurs when trying to access ANY property of the list.
I have a stripped down version of the app that shows the crash available.
To replicate the issue:
open the project in Xcode 26
target any iOS 26 device or simulator
compile and run the project.
after the list is displayed, wait about 15 seconds and the app crashes.
It is also of note that if you try to run the app again, it will crash immediately, unless you delete the app from the device.
Any help on this would be appreciated.
Feedback number FB20295815 includes .zip file
Below is the basic code (without the data models)
The Best Seller List.Swift
import SwiftUI
import SwiftData
@main
struct Best_Seller_ListApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer (for: NYTOverviewResponse.self)
}
}
ContentView.Swift
import os.log
import SwiftUI
struct ContentView: View {
@Environment(\.modelContext) var modelContext
@State private var listEncodedName = String()
var body: some View {
NavigationStack () {
ListsView()
}
.task {
await getBestSellerLists()
}
}
func getBestSellerLists() async {
guard let url = URL(string: "https://api.nytimes.com/svc/books/v3/lists/overview.json?api-key=\(NYT_API_KEY)") else {
Logger.errorLog.error("Invalid URL")
return
}
do {
let decoder = JSONDecoder()
var decodedResponse = NYTOverviewResponse()
//decode the JSON
let (data, _) = try await URLSession.shared.data(from: url)
decoder.keyDecodingStrategy = .convertFromSnakeCase
decodedResponse = try decoder.decode(NYTOverviewResponse.self, from: data)
//remove any lists that don't have list_name_encoded. Fixes a bug in the data
decodedResponse.results!.lists = decodedResponse.results!.lists!.filter { $0.listNameEncoded != "" }
// sort the lists
decodedResponse.results!.lists!.sort { (lhs, rhs) -> Bool in
lhs.displayName < rhs.displayName
}
//delete any potential existing data
try modelContext.delete(model: NYTOverviewResponse.self)
//add the new data
modelContext.insert(decodedResponse)
} catch {
Logger.errorLog.error("\(error.localizedDescription)")
}
}
}
ListsView.Swift
import os.log
import SwiftData
import SwiftUI
@MainActor
struct ListsView: View {
//MARK: - Variables and Constants
@Query var nytOverviewResponses: [NYTOverviewResponse]
enum Updated: String {
case weekly = "WEEKLY"
case monthly = "MONTHLY"
}
//MARK: - Main View
var body: some View {
List {
if nytOverviewResponses.isEmpty {
ContentUnavailableView("No lists yet", systemImage: "list.bullet", description: Text("NYT Bestseller lists not downloaded yet"))
} else {
WeeklySection
MonthlySection
}
}
.navigationBarTitle("Bestseller Lists", displayMode: .large)
.listStyle(.grouped)
}
var WeeklySection: some View {
let rawLists = nytOverviewResponses.last?.results?.lists ?? []
// Build a value-typed array to avoid SwiftData faulting during sort
let weekly = rawLists
.filter { $0.updateFrequency == Updated.weekly.rawValue }
.map { (name: $0.displayName, encoded: $0.listNameEncoded, model: $0) }
.sorted { $0.name < $1.name }
return Section(header: Text("Weekly lists to be published on \(nytOverviewResponses.last?.results?.publishedDate ?? "-")")) {
ForEach(weekly, id: \.encoded) { item in
Text(item.name).font(Font.custom("Georgia", size: 17))
}
}
}
var MonthlySection: some View {
let rawLists = nytOverviewResponses.last?.results?.lists ?? []
// Build a value-typed array to avoid SwiftData faulting during sort
let monthly = rawLists
.filter { $0.updateFrequency == Updated.monthly.rawValue }
.map { (name: $0.displayName, encoded: $0.listNameEncoded, model: $0) }
.sorted { $0.name < $1.name }
return Section(header: Text("Monthly lists to be published on \(nytOverviewResponses.last?.results?.publishedDate ?? "-")")) {
ForEach(monthly, id: \.encoded) { item in
Text(item.name).font(Font.custom("Georgia", size: 17))
}
}
}
}
Hi all,
In my SwiftUI / SwiftData / Cloudkit app which is a series of lists, I have a model object called Project which contains an array of model objects called subprojects:
final class Project1
{
var name: String = ""
@Relationship(deleteRule: .cascade, inverse: \Subproject.project) var subprojects : [Subproject]?
init(name: String)
{
self.name = name
self.subprojects = []
}
}
The user will select a project from a list, which will generate a list of subprojects in another list, and if they select a subproject, it will generate a list categories and if the user selects a category it will generate another list of child objects owned by category and on and on.
This is the pattern in my app, I'm constantly passing arrays of model objects that are the children of other model objects throughout the program, and I need the user to be able to add and remove things from them.
My initial approach was to pass these arrays as bindings so that I'd be able to mutate them. This worked for the most part but there were two problems: it was a lot of custom binding code and when I had to unwrap these bindings using init?(_ base: Binding<Value?>), my program would crash if one of these arrays became nil (it's some weird quirk of that init that I don't understand at al).
As I'm still learning the framework, I had not realized that the @model macro had automatically made my model objects observable, so I decided to remove the bindings and simply pass the arrays by reference, and while it seems these references will carry the most up to date version of the array, you cannot mutate them unless you have access to the parent and mutate it like such:
project.subcategories?.removeAll { $0 == subcategory }
project.subcategories?.append(subcategory)
This is weirding me out because you can't unwrap subcategories before you try to mutate the array, it has to be done like above. In my code, I like to unwrap all optionals at the moment that I need the values stored in them and if not, I like to post an error to the user. Isn't that the point of optionals? So I don't understand why it's like this and ultimately am wondering if I'm using the correct design pattern for what I'm trying to accomplish or if I'm missing something? Any input would be much appreciated!
Also, I do have a small MRE project if the explanation above wasn't clear enough, but I was unable to paste in here (too long), attach the zip or paste a link to Google Drive. Open to sharing it if anyone can tell me the best way to do so. Thanks!
Hi everyone,
Complete newbie here. Building an app and trying to use Cloudkit. I've added the CloudKit capability, triple checked the entitlements file for appropriate keys, made sure the code signing entitlements are pointing to the correct entitlements file. I've removed and cleared all of those settings and even created a new container as well as refreshed the signing. I just can't seem to figure out why I keep getting this error:
Significant issue at CKContainer.m:747: In order to use CloudKit, your process must have a com.apple.developer.icloud-services entitlement. The value of this entitlement must be an array that includes the string "CloudKit" or "CloudKit-Anonymous".
Any guidance is greatly appreciated.
我正在使用 Core Data 开发一个 SwiftUI 项目。我的数据模型中有一个名为 AppleUser 的实体,具有以下属性:id (UUID)、name (String)、email (String)、password (String) 和 createdAt (Date)。所有属性都是非可选的。
我使用 Xcode 的自动生成创建了相应的 Core Data 类文件(AppleUser+CoreDataClass.swift 和 AppleUser+CoreDataProperties.swift)。我还有一个 PersistenceController,它使用模型名称 JobLinkModel 初始化 NSPersistentContainer。
当我尝试使用以下方法保存新的 AppleUser 对象时:
让用户 = AppleUser(上下文:viewContext)
user.id = UUID()
user.name = “用户 1”
user.email = “...”
user.password = “密码 1”
user.createdAt = Date()【电子邮件格式正确,但已替换为“...”出于隐私原因】
尝试?viewContext.save()
我在控制台中收到以下错误:核心数据保存失败:Foundation._GenericObjCError.nilError, [:]
用户快照: [“id”: ..., “name”: “User1”, “email”: “...”, “password”: “...”, “createdAt”: ...]
所有字段都有有效值,核心数据模型似乎正确。我还尝试过:
• 检查 NSPersistentContainer(name:) 中的模型名称是否与 .xcdatamodeld 文件 (JobLinkModel) 匹配
• 确保正确设置 AppleUser 实体类、模块和 Codegen(类定义、当前产品模块)
• 删除重复或旧的 AppleUser 类文件
• 清理 Xcode 构建文件夹并从模拟器中删除应用程序
• 对上下文使用 @Environment(.managedObjectContext)
尽管如此,在保存新的 AppleUser 对象时,我仍然会收到 _GenericObjCError.nilError。
我想了解:
为什么即使所有字段都不是零且正确分配,核心数据也无法保存?
这可能是由于一些残留的旧类文件引起的,还是我缺少设置中的其他内容?
我应该采取哪些步骤来确保 Core Data 正确识别 AppleUser 实体并允许保存?
任何帮助或指导将不胜感激。
Hi,
I’m running into an issue with Core Data migrations using a custom NSMappingModel created entirely in Swift (not using .xcmappingmodel files).
Setup:
• I’m performing a migration with a manually constructed NSMappingModel
• One of the NSEntityMapping instances is configured as follows:
• mappingType = .customEntityMappingType (or .transformEntityMappingType)
• entityMigrationPolicyClassName is set to a valid subclass of NSEntityMigrationPolicy
• The class implements the expected methods like:
@objc func createDestinationInstances(…) throws { … }
@objc func createCustomDestinationInstance(…) throws -> NSManagedObject { … }
The policy class is instantiated (confirmed via logging in init()),
but none of the migration methods are ever called.
I have also tried adding valid NSPropertyMapping instances with real valueExpression bindings to force activation, but that didn’t make a difference.
Constraints:
• I cannot use .xcmappingmodel files in this context due to transformable attributes not compatible with the visual editor.
• Therefore, I need the entire mapping model to be defined in Swift.
Workaround:
As a temporary workaround, I’m migrating the data manually using two persistent stores and NSManagedObjectContext, but I’d prefer to rely on NSMigrationManager as designed.
Question:
Is there a known limitation that prevents Core Data from invoking NSMigrationPolicy methods when using in-memory NSMappingModel instances?
Or is there any specific setup required to trigger them when not loading from .xcmappingmodel?
Thanks in advance.
I'm implementing SwiftData with inheritance in an app.
I have an Entity class with a property name. This class is inherited by two other classes: Store and Person. The Entity model has a one-to-many relationship with a Transaction class.
I can list all my Entity models in a List with a @Query annotation without a problem.
However, then I try to access the name property of an Entity from a Transaction relationship, the app crashes with the following error:
Thread 1: Fatal error: Never access a full future backing data - PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(backing: SwiftData.PersistentIdentifier.PersistentIdentifierBacking.managedObjectID(0x96530ce28d41eb63 <x-coredata://DABFF7BB-C412-474E-AD50-A1F30AC6DBE9/Person/p4>))) with Optional(F07E7E23-F8F0-4CC0-B282-270B5EDDC7F3)
From my attempts to fix the issue, I noticed that:
The crash seems related to the relationships with classes that has inherit from another class, since it only happens there.
When I create new data, I can usually access it without any problem. The crash mostly happens after reloading the app.
This error has been mentioned on the forum (for example here), but in a context not related with inheritance.
You can find the full code here.
For reference, my models looks like this:
@Model
class Transaction {
@Attribute(.unique)
var id: String
var name: String
var date: Date
var amount: Double
var entity: Entity?
var store: Store? { entity as? Store }
var person: Person? { entity as? Person }
init(
id: String = UUID().uuidString,
name: String,
amount: Double,
date: Date = .now,
entity: Entity? = nil,
) {
self.id = id
self.name = name
self.amount = amount
self.date = date
self.entity = entity
}
}
@Model
class Entity: Identifiable {
@Attribute(.preserveValueOnDeletion)
var name: String
var lastUsedAt: Date
@Relationship(deleteRule: .cascade, inverse: \Transaction.entity)
var operations: [Transaction]
init(
name: String,
lastUsedAt: Date = .now,
operations: [Transaction] = [],
) {
self.name = name
self.lastUsedAt = lastUsedAt
self.operations = operations
}
}
@available(iOS 26, *)
@Model
class Store: Entity {
@Attribute(.unique) var id: String
var locations: [Location]
init(
id: String = UUID().uuidString,
name: String,
lastUsedAt: Date = .now,
locations: [Location] = [],
operations: [Transaction] = []
) {
self.locations = locations
self.id = id
super.init(name: name, lastUsedAt: lastUsedAt, operations: operations)
}
}
In order to reproduce the error:
Run the app in the simulator.
Click the + button to create a new transaction.
Relaunch the app, then click on any transaction.
The app crashes when it tries to read te name property while building the details view.
I'm working on a new app with SwiftData and now adding CloudKit Sync.
Everything is working fine in the simulator against the development CloudKit Schema. I successfully deployed the schema to production.
However, the TestFlight builds fail against production. This is what I see in the logs, but I haven't been able to find info on how to fix it.
Help appreciated.
CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](2205): <private> - Never successfully initialized and cannot execute request '<private>' due to error: Error Domain=CKErrorDomain Code=2 "CKInternalErrorDomain: 1011" UserInfo={ContainerID=<private>, NSDebugDescription=CKInternalErrorDomain: 1011, CKPartialErrors=<private>, RequestUUID=<private>, NSLocalizedDescription=<private>, CKErrorDescription=<private>, NSUnderlyingError=0x1078e9fe0 {Error Domain=CKInternalErrorDomain Code=1011 UserInfo={CKErrorDescription=<private>, NSLocalizedDescription=<private>, CKPartialErrors=<private>}}}
CoreData+CloudKit: -[NSCloudKitMirroringDelegate _performSetupRequest:]_block_invoke(1153): <private>: Successfully set up CloudKit integration for store (<private>): <private>
CoreData+CloudKit: -[NSCloudKitMirroringDelegate _enqueueRequest:]_block_invoke(1035): Failed to enqueue request: <private>
Error Domain=NSCocoaErrorDomain Code=134417 UserInfo={NSLocalizedFailureReason=<private>}
I am working on a SwiftUI project using Core Data. I have an entity called AppleUser in my data model, with the following attributes: id (UUID), name (String), email (String), password (String), and createdAt (Date). All attributes are non-optional.
I created the corresponding Core Data class files (AppleUser+CoreDataClass.swift and AppleUser+CoreDataProperties.swift) using Xcode’s automatic generation. I also have a PersistenceController that initializes the NSPersistentContainer with the model name JobLinkModel.
When I try to save a new AppleUser object using:
let user = AppleUser(context: viewContext)
user.id = UUID()
user.name = "User1"
user.email = "..."
user.password = "password1"
user.createdAt = Date()【The email is correctly formatted, but it has been replaced with “…” for privacy reasons】
try? viewContext.save()
I get the following error in the console:Core Data save failed: Foundation._GenericObjCError.nilError, [:]
User snapshot: ["id": ..., "name": "User1", "email": "...", "password": "...", "createdAt": ...]
All fields have valid values, and the Core Data model seems correct. I have also tried:
• Checking that the model name in NSPersistentContainer(name:) matches the .xcdatamodeld file (JobLinkModel)
• Ensuring the AppleUser entity Class, Module, and Codegen are correctly set (Class Definition, Current Product Module)
• Deleting duplicate or old AppleUser class files
• Cleaning Xcode build folder and deleting the app from the simulator
• Using @Environment(.managedObjectContext) for the context
Despite all this, I still get _GenericObjCError.nilError when saving a new AppleUser object.
I want to understand:
1. Why is Core Data failing to save even though all fields are non-nil and correctly assigned?
2. Could this be caused by some residual old class files, or is there something else in the setup that I am missing?
3. What steps should I take to ensure that Core Data properly recognizes the AppleUser entity and allows saving?
Any help or guidance would be greatly appreciated.
I have been working on an app for the past few months, and one issue that I have encountered a few times is an error where quick subsequent deletions cause issues with detached tasks that are triggered from some user actions.
Inside a Task.detached, I am building an isolated model context, querying for LineItems, then iterating over those items. The crash happens when accessing a Transaction property through a relationship.
var byTransactionId: [UUID: [LineItem]] {
return Dictionary(grouping: self) { item in
item.transaction?.id ?? UUID()
}
}
In this case, the transaction has been deleted, but the relationship existed when the fetch occurred, so the transaction value is non-nil. The crash occurs when accessing the id. This is the error.
SwiftData/BackingData.swift:1035: Fatal error: This model instance was invalidated because its backing data could no longer be found the store. PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(backing: SwiftData.PersistentIdentifier.PersistentIdentifierBacking.managedObjectID(0xb43fea2c4bc3b3f5 <x-coredata://A9EFB8E3-CB47-48B2-A7C4-6EEA25D27E2E/Transaction/p1756>)))
I see other posts about this error and am exploring some suggestions, but if anyone has any thoughts, they would be appreciated.
Good morning everyone!
Today I have a question about using SwiftData with CloudKit and Widgets. I recently set up my project for SwiftData and CloudKit synchronization, but for some reason, I’m not able to give my Widget access to this data. CloudKit works perfectly fine for my main app, but the Widget only shows placeholder data(the placeholder data which were defined in the get functions as catch, this is sure).
I have set the CloudKit capability for my Widget extension and tried fetching data with the get-functions in the code below. I also ensured that the data model files are members of the Widget extension target and that the Widget extension uses the same CloudKit container as the main app.
I wondered if it is possible and reasonable to save a copy of my CloudKit data in an App Group container, but in that case, the information shown in the Widget are not always up-to-date, so a solution that fetches data directly from CloudKit would be better. Has anyone had experience with this case? I couldn’t find much information about this problem online.
In the code below, many parts have been deleted or altered because they are not relevant to the problem, as they don’t fetch data. The variables, functions, and data models in the code may sometimes have German names, but I hope you can still understand it.
Thanks for your help!
struct Provider: AppIntentTimelineProvider {
//[Placeholder and snapshot]
func timeline(for configuration: ConfigurationAppIntent, in context: Context) async -> Timeline<CleverEntry> {
let entry = await loadAllVariables()
return Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(60 * 5)))
}
@MainActor
private func getExam() -> [PruefungM] {
//Old, local version
/*
guard let modelContainer = try? ModelContainer(for: PruefungM.self) else {
return []
}
let descriptor = FetchDescriptor<PruefungM>()
let PRF = try? modelContainer.mainContext.fetch(descriptor)
return PRF ?? []
*/
do {
let configuration = ModelConfiguration(cloudKitDatabase: .private("iCloud.my_bundle_id"))
let container = try ModelContainer(
for: PruefungM.self,
configurations: configuration
)
let descriptor = FetchDescriptor<PruefungM>()
return try container.mainContext.fetch(descriptor)
} catch {
print("❌ Error(CloudKit): \(error)")
return []
}
}
@MainActor
private func getHAF() -> [HausaufgabeM] {
do {
let configuration = ModelConfiguration(cloudKitDatabase: .private("iCloud.my_bundle_id"))
let container = try ModelContainer(
for: HausaufgabeM.self,
configurations: configuration
)
let descriptor = FetchDescriptor<HausaufgabeM>()
return try container.mainContext.fetch(descriptor)
} catch {
print("❌ Error (CloudKit): \(error)")
return []
}
}
@MainActor
private func loadAllVariables() -> CleverEntry {
print("Function started")
let HAF = getHAF()
let PRF = getExam()
//handling and returning the data
}
}
I'm trying to use the new (in tvOS 26) video streaming service automatic login API from the VideoSubscriberAccount framework:
https://developer.apple.com/documentation/videosubscriberaccount/vsuseraccountmanager/autosignintoken-swift.property
It seems that this API requires an entitlement. This document suggests that the com.apple.smoot.subscriptionservice entitlement is required.
https://developer.apple.com/documentation/videosubscriberaccount/signing-people-in-to-media-apps-automatically
However, it seems more likely that com.apple.developer.video-subscriber-single-sign-on is the correct entitlement.
https://developer.apple.com/documentation/bundleresources/entitlements/com.apple.developer.video-subscriber-single-sign-on
Which is the correct entitlement and how do I obtain it?
I don't want to fully comply with the video partner program.
https://developer.apple.com/programs/video-partner/
I just want to use this one new automatic login feature.
Hi everyone,
Im trying to set up CloudKit for my Unreal Engine 5.4 project but seem to be hitting some roadblocks on how to set up the Record Types.
From my understanding I need to set up a "file" record type with a "contents" asset field - but even with this it doesn't seem to work :(
Any unreal engine devs with some experience on this who could help me out?
Thanks!
Hello everyone,
I am experiencing a persistent authentication error when querying a custom user profile record, and the error message seems to be a red herring.
My Setup:
I have a custom CKRecord type called ColaboradorProfile.
When a new user signs up, I create this record and store their hashed password, salt, nickname, and a custom field called loginIdentifier (which is just their lowercase username).
In the CloudKit Dashboard, I have manually added an index for loginIdentifier and set it to Queryable and Searchable. I have deployed this schema to Production.
The Problem:
During login, I run an async function to find the user's profile using this indexed loginIdentifier.
Here is the relevant authentication code:
func autenticar() async {
// ... setup code (isLoading, etc.)
let lowercasedUsername = username.lowercased()
// My predicate ONLY filters on 'loginIdentifier'
let predicate = NSPredicate(format: "loginIdentifier == %@", lowercasedUsername)
let query = CKQuery(recordType: "ColaboradorProfile", predicate: predicate)
// I only need these specific keys
let desiredKeys = ["password", "passwordSalt", "nickname", "isAdmin", "isSubAdmin", "username"]
let database = CKContainer.default().publicCloudDatabase
do {
// This is the line that throws the error
let result = try await database.records(matching: query, desiredKeys: desiredKeys, resultsLimit: 1)
// ... (rest of the password verification logic)
} catch {
// The error always lands here
logDebug("Error authenticating with CloudKit: \(error.localizedDescription)")
await MainActor.run {
self.errorMessage = "Connection Error: \(error.localizedDescription)"
self.isLoading = false
self.showAlert = true
}
}
}
The Error:
Even though my query predicate only references loginIdentifier, the catch block consistently reports this error:
Error authenticating with CloudKit: Field 'createdBy' is not marked queryable.
I know createdBy (the system creatorUserRecordID) is not queryable by default, but my query isn't touching that field. I already tried indexing createdBy just in case, but the error persists. It seems CloudKit cannot find or use my index for loginIdentifier and is incorrectly reporting a fallback error related to a system field.
Has anyone seen this behavior? Why would CloudKit report an error about createdBy when the query is explicitly on an indexed, custom field?
I'm new to Swift and I'm struggling quite a bit.
Thank you,
I'm trying to set up an application using SwiftData to have a number of models backed by a local datastore that's not synced to CloudKit, and another set of models that is. I was able to achieve this previously with Core Data using multiple NSPersistentStoreDescription instances.
The set up code looks something like:
do {
let fullSchema = Schema([
UnsyncedModel.self,
SyncedModel.self,
])
let localSchema = Schema([UnsyncedModel.self])
let localConfig = ModelConfiguration(schema: localSchema, cloudKitDatabase: .none)
let remoteSchema = Schema([SyncedModel.self])
let remoteConfig = ModelConfiguration(schema: remoteSchema, cloudKitDatabase: .automatic)
container = try ModelContainer(for: fullSchema, configurations: localConfig, remoteConfig)
} catch {
fatalError("Failed to configure SwiftData container.")
}
However, it doesn't seem to work as expected. If I remove the synced/remote schema and configuration then everything works fine, but the moment I add in the remote schema and configuration I get various different application crashes. Some examples below:
A Core Data error occurred." UserInfo={Reason=Entity named:... not found for relationship named:...,
Fatal error: Failed to identify a store that can hold instances of SwiftData._KKMDBackingData<...>
Has anyone ever been able to get a similar setup to work using SwiftData?
I am developing an app that uses CloudKit sharing. I recently upgraded my iPad to use 23A5336a. After that upgrade, I can no longer accept a share that is sent to me.
I have rebooted the iPad and logged out of the iCloud account and logged back in. Every time I get a share link and tap it, it says:
" The owner stopped sharing or your account (***) doesn't have permission to open it"
This same code, running on the iOS26 device can share with device running iOS18.
Is this a known defect? Anything I can do to help resolve this issue?
I'm developing an app that uses CloudKit synchronization with SwiftData and on visionOS I added an App Settings bundle. I have noticed that sometimes, when the app is open and the user changes a setting from the App Settings bundle, the following fatal error occurs:
SwiftData/BackingData.swift:831: Fatal error: This model instance was destroyed by calling ModelContext.reset and is no longer usable.
The setting is read within the App struct in the visionOS app target using @AppStorage and this value is in turn used to set the passthrough video dimming via the .preferredSurroundingsEffect modifier. The setting allows the user to specify the dimming level as dark, semi dark, or ultra dark.
The fatal error appears to occur intermittently although the first time it was observed was after adding the settings bundle. As such, I suspect there is some connection between those code changes and this fatal error even though they do not directly relate to SwiftData.
I have an app that from day 1 has used Swiftdata and successfully sync'd across devices with Cloudkit. I have added models to the data in the past and deployed the schema and it continued to sync across devices. Sometime I think in June.2025 I added a new model and built out the UI to display and manage it. I pushed a version to Test Flight (twice over a matter of 2 versions and a couple of weeks) and created objects in the new model in Test Flight versions of the app which should push the info to Cloudkit to update the schema.
When I go to deploy the schema though there are no changes. I confirmed in the app that Cloudkit is selected and it's point to the correct container. And when I look in Cloudkit the new model isn't listed as an indes.
I've pushed deploy schema changes anyway (more than once) and now the app isn't sync-ing across devices at all (even the pre-existing models aren't sync-ing across devices).
I even submitted the first updated version to the app store and it was approved and released. I created objects in the new model in production which I know doesn't create the indexes in the development environment. But this new model functions literally everywhere except Cloudkit and I don't know what else to do to trigger an update.
My entity has a startDate (NSTime) attribute where I use the date and time in my detail display of the entity.
And in my list, I need to group my entities by day (YYMMDD) based on the start date; and I want to ensure that it can adapt to the region where the user is currently (e.g. if user travels or migrate, the YYMMDD should be adapted based on the current region). Does Core Data SectionedFetchRequest supports strftime() functions from SQLite (https://sqlite.org/lang_datefunc.html) or what is an effective alternative sectioned fetch in my case?
Users have been reporting that the TestFlight version of my app (compiled with Xcode 26 Beta 6 17A5305f) is sometimes crashing on startup. Upon investigating their ips files, it looks like Core Data is locking up internally during its initialization, resulting in iOS killing my app. I have not recently changed my Core Data initialization logic, and it's unclear how I should proceed.
Is this a known issue? Any recommended workaround? I have attached the crash stack below.
Thanks!
crash_log.txt