Definitely one of the stranger quirks of SwiftData I've come across.
I have a ScriptView that shows Line entities related to a Production, and a TextEnterScriptView that’s presented in a sheet to input text.
I’m noticing that every time I type in the TextEditor within TextEnterScriptView, a new Line shows up in ScriptView — even though I haven’t explicitly inserted it into the modelContext.
I'm quite confused because even though I’m only assigning a new Line to a local @State array in TextEnterScriptView, every keystroke in the TextEditor causes a duplicate Line to appear in ScriptView.
In other words, Why is SwiftData creating new Line entities every time I type in the TextEditor, even though I’m only assigning to a local @State array and not explicitly inserting them into the modelContext?
Here is my minimal reproducible example:
import SwiftData
import SwiftUI
@main
struct testApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.modelContainer(for: Line.self, isAutosaveEnabled: false)
}
}
}
struct ContentView: View {
@Environment(\.modelContext) var modelContext
@Query(sort: \Production.title) var productions: [Production]
var body: some View {
NavigationStack {
List(productions) { production in
NavigationLink(value: production) {
Text(production.title)
}
}
.navigationDestination(for: Production.self) { production in
ScriptView(production: production)
}
.toolbar {
Button("Add", systemImage: "plus") {
let production = Production(title: "Test \(productions.count + 1)")
modelContext.insert(production)
do {
try modelContext.save()
} catch {
print(error)
}
}
}
.navigationTitle("Productions")
}
}
}
struct ScriptView: View {
@Query private var lines: [Line]
let production: Production
@State private var isShowingSheet: Bool = false
var body: some View {
List {
ForEach(lines) { line in
Text(line.content)
}
}
.toolbar {
Button("Show Sheet") {
isShowingSheet.toggle()
}
}
.sheet(isPresented: $isShowingSheet) {
TextEnterScriptView(production: production)
}
}
}
struct TextEnterScriptView: View {
@Environment(\.dismiss) var dismiss
@State private var text = ""
@State private var lines: [Line] = []
let production: Production
var body: some View {
NavigationStack {
TextEditor(text: $text)
.onChange(of: text, initial: false) {
lines = [Line(content: "test line", production: production)]
}
.toolbar {
Button("Done") {
dismiss()
}
}
}
}
}
@Model
class Production {
@Attribute(.unique) var title: String
@Relationship(deleteRule: .cascade, inverse: \Line.production)
var lines: [Line] = []
init(title: String) {
self.title = title
}
}
@Model
class Line {
var content: String
var production: Production?
init(content: String, production: Production?) {
self.content = content
self.production = production
}
}
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
The following complex migration consistently crashes the app with the following error:
SwiftData/PersistentModel.swift:726: Fatal error: What kind of backing data is this? SwiftData._KKMDBackingData<SwiftDataMigration.ItemSchemaV1.ItemList>
My app relies on a complex migration that involves these optional 1 to n relationships. Theoretically I could not assign the relationships in the willMigrate block but afterwards I am not able to tell which list and items belonged together.
Steps to reproduce:
Run project
Change typealias CurrentSchema to ItemSchemaV2 instead of ItemSchemaV1.
Run project again -> App crashes
My setup:
Xcode Version 16.2 (16C5032a)
MacOS Sequoia 15.4
iPhone 12 with 18.3.2 (22D82)
Am I doing something wrong or did I stumble upon a bug? I have a demo Xcode project ready but I could not upload it here so I put the code below.
Thanks for your help
typealias CurrentSchema = ItemSchemaV1
typealias ItemList = CurrentSchema.ItemList
typealias Item = CurrentSchema.Item
@main
struct SwiftDataMigrationApp: App {
var sharedModelContainer: ModelContainer = {
do {
return try ModelContainer(for: ItemList.self, migrationPlan: MigrationPlan.self)
} catch {
fatalError("Could not create ModelContainer: \(error)")
}
}()
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(sharedModelContainer)
}
}
This is the migration plan
enum MigrationPlan: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[ItemSchemaV1.self, ItemSchemaV2.self]
}
static var stages: [MigrationStage] = [
MigrationStage.custom(fromVersion: ItemSchemaV1.self, toVersion: ItemSchemaV2.self, willMigrate: { context in
print("Started migration")
let oldlistItems = try context.fetch(FetchDescriptor<ItemSchemaV1.ItemList>())
for list in oldlistItems {
let items = list.items.map { ItemSchemaV2.Item(timestamp: $0.timestamp)}
let newList = ItemSchemaV2.ItemList(items: items, name: list.name, note: "This is a new property")
context.insert(newList)
context.delete(list)
}
try context.save() // Crash indicated here
print("Finished willMigrate")
}, didMigrate: { context in
print("Did migrate successfully")
})
]
}
The versioned schemas
enum ItemSchemaV1: VersionedSchema {
static var versionIdentifier = Schema.Version(1, 0, 0)
static var models: [any PersistentModel.Type] {
[Item.self]
}
@Model
final class Item {
var timestamp: Date
var list: ItemSchemaV1.ItemList?
init(timestamp: Date) {
self.timestamp = timestamp
}
}
@Model
final class ItemList {
@Relationship(deleteRule: .cascade, inverse: \ItemSchemaV1.Item.list)
var items: [Item]
var name: String
init(items: [Item], name: String) {
self.items = items
self.name = name
}
}
}
enum ItemSchemaV2: VersionedSchema {
static var versionIdentifier = Schema.Version(2, 0, 0)
static var models: [any PersistentModel.Type] {
[Item.self]
}
@Model
final class Item {
var timestamp: Date
var list: ItemSchemaV2.ItemList?
init(timestamp: Date) {
self.timestamp = timestamp
}
}
@Model
final class ItemList {
@Relationship(deleteRule: .cascade, inverse: \ItemSchemaV2.Item.list)
var items: [Item]
var name: String
var note: String
init(items: [Item], name: String, note: String = "") {
self.items = items
self.name = name
self.note = note
}
}
}
Last the ContentView:
struct ContentView: View {
@Query private var itemLists: [ItemList]
var body: some View {
NavigationSplitView {
List {
ForEach(itemLists) { list in
NavigationLink {
List(list.items) { item in
Text(item.timestamp.formatted(date: .abbreviated, time: .complete))
}
.navigationTitle(list.name)
} label: {
Text(list.name)
}
}
}
.navigationTitle("Crashing migration demo")
.onAppear {
if itemLists.isEmpty {
for index in 0..<10 {
let items = [Item(timestamp: Date.now)]
let listItem = ItemList(items: items, name: "List No. \(index)")
modelContext.insert(listItem)
}
try! modelContext.save()
}
}
} detail: {
Text("Select an item")
}
}
}
I've noticed that SwiftData's @Relationship seems to potentially cause application crashes.
The crash error is shown in the image.
Since this crash appears to be random and I cannot reproduce it under specific circumstances, I can only temporarily highlight that this issue seems to exist.
@Model final class TrainInfo {
@Relationship(deleteRule: .cascade, inverse: \StopStation.trainInfo)
var stations: [StopStation]?
}
@Model final class StopStation {
@Relationship
var trainInfo: TrainInfo?
}
/// some View
var origin: StopStationDisplayable? {
if let train = train as? TrainInfo {
return train.stations?.first(where: { $0.isOrigin }) ?? train.stations?.first(where: { $0.isStarting })
}
return nil
}
// Some other function or property
func someFunction() {
if let origin, let destination {
// Function implementation
}
}
There's some logic in my app that first checks to see if a specific CloudKit record zone exists. If it doesn't, it creates the zone, and then my application continues on with its work.
The way I've implemented this right now is by catching the zoneNotFound error when I call CKDatabase#recordZone(for:) (docs) and creating the zone when that happens:
do {
try await db.recordZone(for: zoneID)
} catch let ckError as CKError
where [.zoneNotFound, .userDeletedZone].contains(ckError.code)
{
// createZone is a helper function
try await createZone(zoneID: zoneID, context: context)
}
This works great, but every time I do this, an error is logged in CloudKit Console, which creates a lot of noise and makes it harder to see real errors.
Is there a way to do this without explicitly triggering a CloudKit error?
I just found CKDatabase#recordZones(for:) (docs), which seems like it returns an empty array instead of throwing an error if the zone doesn't exist.
Will calling that and looking for a non-empty array work just as well, but without logging lots of errors in the console?
Hello everyone,
I'm trying to adopt the new Staged Migrations for Core Data and I keep running into an error that I haven't been able to resolve.
The error messages are as follows:
warning: Multiple NSEntityDescriptions claim the NSManagedObject subclass 'Movie' so +entity is unable to disambiguate.
warning: 'Movie' (0x60000350d6b0) from NSManagedObjectModel (0x60000213a8a0) claims 'Movie'.
error: +[Movie entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass
This happens for all of my entities when they are added/fetched. Movie is an abstract entity subclass, and it has the error error: +[Movie entity] Failed to find which is unique to the subclass entities, but this occurs for all entities.
The NSPersistentContainer is loaded only once, and I set the following option after it's loaded:
storeDescription.setOption(
[stages],
forKey: NSPersistentStoreStagedMigrationManagerOptionKey
)
The warnings and errors only appear after I fetch or save to context. It happens regardless of whether the database was migrated or not. In my test project, using the generic NSManagedObject with NSEntityDescription.insertNewObject(forEntityName: "MyEntity", into: context) does not cause the issue. However, using the generic NSManagedObject is not a viable option for my app.
Setting the module to "Current Project Module" doesn't change anything, except that it now prints "claims 'MyModule.Show'" in the warnings. I have verified that there are no other entities with the same name or renameIdentifier.
Has anyone else encountered this issue, or can offer any suggestions on how to resolve it?
Thanks in advance for any help!
I'm looking for guidance how to mitigate this crash. It seems super deep inside Core Data' FRC fetchedObjects management.
In my code, it's initiated by this
viewContext.perform {
[unowned self] in
self.viewContext.mergeChanges(fromContextDidSave: notification)
}
which is directly followed by the stack trace below.
Basically merging data from .NSManagedObjectContextDidSave notification from another NSManagedObjectContext. Nothing special, it works great for years, apart from these rare occurrences.
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Reason: -[__NSCFArray objectAtIndex:]: index (235) beyond bounds (234)
Termination Reason: SIGNAL 6 Abort trap: 6
Triggered by Thread: 0
Last Exception Backtrace:
0 CoreFoundation 0x199e947cc __exceptionPreprocess + 164 (NSException.m:249)
1 libobjc.A.dylib 0x1971672e4 objc_exception_throw + 88 (objc-exception.mm:356)
2 CoreFoundation 0x199fc4258 _NSArrayRaiseBoundException + 368 (NSCFArray.m:22)
3 CoreFoundation 0x199e288a4 -[__NSCFArray objectAtIndex:] + 200 (NSCFArray.m:42)
4 CoreData 0x1a1e17338 -[_PFMutableProxyArray objectAtIndex:] + 40 (_PFArray.m:1860)
5 CoreData 0x1a1e1673c -[NSFetchedResultsController _updateFetchedObjectsWithInsertChange:] + 380 (NSFetchedResultsController.m:1582)
6 CoreData 0x1a1e1426c __82-[NSFetchedResultsController(PrivateMethods) _core_managedObjectContextDidChange:]_block_invoke + 2240 (NSFetchedResultsController.m:2171)
7 CoreData 0x1a1dcdf80 developerSubmittedBlockToNSManagedObjectContextPerform + 156 (NSManagedObjectContext.m:4002)
8 CoreData 0x1a1e41a44 -[NSManagedObjectContext performBlockAndWait:] + 216 (NSManagedObjectContext.m:4113)
9 CoreData 0x1a1e41034 -[NSFetchedResultsController _core_managedObjectContextDidChange:] + 124 (NSFetchedResultsController.m:2379)
10 CoreFoundation 0x199e632f4 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 148 (CFNotificationCenter.c:701)
11 CoreFoundation 0x199e63210 ___CFXRegistrationPost_block_invoke + 88 (CFNotificationCenter.c:194)
12 CoreFoundation 0x199e63158 _CFXRegistrationPost + 436 (CFNotificationCenter.c:222)
13 CoreFoundation 0x199e6170c _CFXNotificationPost + 728 (CFNotificationCenter.c:1248)
14 Foundation 0x198a84ea4 -[NSNotificationCenter postNotificationName:object:userInfo:] + 92 (NSNotification.m:531)
15 CoreData 0x1a1e11650 -[NSManagedObjectContext _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:] + 1736 (NSManagedObjectContext.m:8098)
16 CoreData 0x1a1e10e0c -[NSManagedObjectContext _postRefreshedObjectsNotificationAndClearList] + 164 (NSManagedObjectContext.m:7631)
17 CoreData 0x1a1e0fad8 -[NSManagedObjectContext _processRecentChanges:] + 100 (NSManagedObjectContext.m:7714)
18 CoreData 0x1a1e3563c -[NSManagedObjectContext _coreMergeChangesFromDidSaveDictionary:usingObjectIDs:withClientQueryGeneration:] + 3436 (NSManagedObjectContext.m:3723)
19 CoreData 0x1a1e34350 __116+[NSManagedObjectContext(_NSCoreDataSPI) _mergeChangesFromRemoteContextSave:intoContexts:withClientQueryGeneration:]_block_invoke_4 + 76 (NSManagedObjectContext.m:9531)
20 CoreData 0x1a1dcdf80 developerSubmittedBlockToNSManagedObjectContextPerform + 156 (NSManagedObjectContext.m:4002)
21 CoreData 0x1a1e41a44 -[NSManagedObjectContext performBlockAndWait:] + 216 (NSManagedObjectContext.m:4113)
22 CoreData 0x1a1e39880 +[NSManagedObjectContext _mergeChangesFromRemoteContextSave:intoContexts:withClientQueryGeneration:] + 2372 (NSManagedObjectContext.m:9537)
23 CoreData 0x1a1e344a0 -[NSManagedObjectContext mergeChangesFromContextDidSaveNotification:] + 292 (NSManagedObjectContext.m:0)
Topic:
App & System Services
SubTopic:
iCloud & Data
If use a SortDescriptor for a model and sort by some attribute from a relationship, in DEBUG mode it all works fine and sorts. However, in release mode, it is an instant crash.
SortDescriptor(.name, order: .reverse) ---- works
SortDescriptor(.assignedUser?.name, order: .reverse) ---- works in debug but crash in release.
What is the issue here, is it that SwiftData just incompetent to do this?
Setup
I am running a versionedSchema for my SwiftData model and attempting a migration. The new version contains a new attribute, with a type of a new custom enum defined in the @Model class, a default value, and a private(set). Migration was completed with a migrationPlan with nil values for willMigrate and didMigrate.
Example - Previous Version
@Model
class MyNumber {
var num: Int
init() {
// Init Code
}
}
Example - Newest Version
@Model
class MyNumber {
var num: Int
private(set) var rounding: RoundAmount = MyNumber.RoundAmount.thirtyMinute
init() {
// Init Code
}
enum RoundAmount {
case fiveMinute, tenMinute, thirtyMinute
}
}
Issue
Running this code, I get a swiftData error for “SwiftData/ModelCoders.swift:1585: nil value passed for a non-optional keyPath, /MyNumber.rounding”
I assume this means a failure of the swiftData lightweight migration? I have reverted the version, removed private(set) and re-tried the migration with no success.
Using the versionedSchema with migrationPlans, are lightweight migrations possible? Could this be an issue with the use of a custom enum? Other changes in my actual project migrated successfully so I’m lost on why I’m having this issue.
Hi there, I got two models here:
Two Models, with Many-To-Many Relationship
@Model
final class PresetParams: Identifiable {
@Attribute(.unique) var id: UUID = UUID()
var positionX: Float = 0.0
var positionY: Float = 0.0
var positionZ: Float = 0.0
var volume: Float = 1.0
@Relationship(deleteRule: .nullify, inverse: \Preset.presetAudioParams)
var preset = [Preset]()
init(position: SIMD3<Float>, volume: Float) {
self.positionX = position.x
self.positionY = position.y
self.positionZ = position.z
self.volume = volume
self.preset = []
}
var position: SIMD3<Float> {
get {
return SIMD3<Float>(x: positionX, y: positionY, z: positionZ)
}
set {
positionX = newValue.x
positionY = newValue.y
positionZ = newValue.z
}
}
}
@Model
final class Preset: Identifiable {
@Attribute(.unique) var id: UUID = UUID()
var presetName: String
var presetDesc: String?
var presetAudioParams = [PresetParams]() // Many-To-Many Relationship.
init(presetName: String, presetDesc: String? = nil) {
self.presetName = presetName
self.presetDesc = presetDesc
self.presetAudioParams = []
}
}
To be honest, I don't fully understand how the @Relationship thing works properly in a Many-To-Many relationship situation. Some tutorials suggest that it's required on the "One" side of an One-To-Many Relationship, while the "Many" side doesn't need it.
And then there is an ObservableObject called "ModelActors" to manage all ModelActors, ModelContainer, etc.
ModelActors, ModelContainer...
class ModelActors: ObservableObject {
static let shared: ModelActors = ModelActors()
let sharedModelContainer: ModelContainer
private init() {
var schema = Schema([
// ...
Preset.self,
PresetParams.self,
// ...
])
do {
sharedModelContainer = try ModelContainer(for: schema, migrationPlan: MigrationPlan.self)
} catch {
fatalError("Could not create ModelContainer: \(error.localizedDescription)")
}
}
}
And there is a migrationPlan:
MigrationPlan
// MARK: V102
// typealias ...
// MARK: V101
typealias Preset = AppSchemaV101.Preset
typealias PresetParams = AppSchemaV101.PresetParams
// MARK: V100
// typealias ...
enum MigrationPlan: SchemaMigrationPlan {
static var schemas: [VersionedSchema.Type] {
[
AppSchemaV100.self,
AppSchemaV101.self,
AppSchemaV102.self,
]
}
static var stages: [MigrationStage] {
[AppMigrateV100toV101, AppMigrateV101toV102]
}
static let AppMigrateV100toV101 = MigrationStage.lightweight(fromVersion: AppSchemaV100.self, toVersion: AppSchemaV101.self)
static let AppMigrateV101toV102 = MigrationStage.lightweight(fromVersion: AppSchemaV101.self, toVersion: AppSchemaV102.self)
}
// MARK: Here is the AppSchemaV101
enum AppSchemaV101: VersionedSchema {
static var versionIdentifier: Schema.Version = Schema.Version(1, 0, 1)
static var models: [any PersistentModel.Type] {
return [ // ...
Preset.self,
PresetParams.self
]
}
}
Fails on iOS 18.3.x: "Failed to fulfill link PendingRelationshipLink"
So I expected the SwiftData subsystem to work correctly with version control. A good news is that on iOS 18.1 it does work. But it fails on iOS 18.3.x with a fatal Error:
"SwiftData/SchemaCoreData.swift:581: Fatal error: Failed to fulfill link PendingRelationshipLink(relationshipDescription: (<NSRelationshipDescription: 0x30377fe80>), name preset, isOptional 0, isTransient 0, entity PresetParams, renamingIdentifier preset, validation predicates (), warnings (), versionHashModifier (null)userInfo {}, destination entity Preset, inverseRelationship (null), minCount 0, maxCount 0, isOrdered 0, deleteRule 1, destinationEntityName: "Preset", inverseRelationshipName: Optional("presetAudioParams")), couldn't find inverse relationship 'Preset.presetAudioParams' in model"
Fails on iOS 17.5: Another Error
I tested it on iOS 17.5 and found another issue: Accessing or mutating the "PresetAudioParams" property causes the SwiftData Macro Codes to crash, affecting both Getter and Setter. It fails with an error:
"EXC_BREAKPOINT (code=1, subcode=0x1cc1698ec)"
Tweaking the @Relationship marker and ModelContainer settings didn't fix the problem.
error: the replacement path doesn't exist <- how bad is this error, should i care - is it important?
I get this error, i have my own DIKit, and i want to use swiftdata for showing info from persisten model. It works all over the app, but i get this error with my .sheet.
// JobCreationView.swift
// Features
//
// Created by Jens Vik on 26/03/2025.
//
import SwiftUI
import DesignKit
import DIKit
import PresentationKit
import CoreKit
import DomainKit
import SwiftData
public struct JobCreationView: View {
@Binding var isPresented: Bool
// Inject view model using DIKit's property wrapper
@Injected((any JobCreationViewModelProtocol).self) private var viewModel
// Form state
@Injected(ModelContext.self) private var modelContext
@State private var date = Date()
@State private var isASAP = false
@State private var price = ""
@State private var jobType = "Fiks"
@State private var description = ""
// Available job types
private let jobTypes = ["Fiks", "Fiksit"]
@Query private var userContexts: [UserContextModel]
public init(isPresented: Binding<Bool>) {
self._isPresented = isPresented
print("DEBUG: JobCreationView initialized")
}
public var body: some View {
let city = userContexts.first?.city ?? "Loading..."
NavigationView {
Form {
Section(header: Text("Location")) {
Text(city)
}
Section(header: Text("Details")) {
TextField("Price", text: $price)
.keyboardType(.numberPad)
Picker("Job Type", selection: $jobType) {
ForEach(jobTypes, id: \.self) { type in
Text(type).tag(type)
}
}
.pickerStyle(SegmentedPickerStyle())
TextEditor(text: $description)
.frame(minHeight: 100)
.overlay(
RoundedRectangle(cornerRadius: 8)
.stroke(Color.gray.opacity(0.2), lineWidth: 1)
)
}
}
.navigationBarTitle("Create Job", displayMode: .inline)
.navigationBarItems(
leading: Button("Cancel") {
isPresented = false
},
trailing: Button("Post") {
// Post functionality will be added later
isPresented = false
}
.disabled( (!isASAP && date < Date()) || price.isEmpty || description.isEmpty)
)
}
}
}
How bad is this macro error?
error: the replacement path doesn't exist: "/var/folders/dn/x3x4wwkd335_rl91by3tqx5w0000gn/T/swift-generated-sources/@_swiftmacro_10FeatureKit15JobCreationViewV12userContexts33_CDDE5BE156468A2E8CC9B6A7E34B1006LL5QueryfMa.swift"
error: the replacement path doesn't exist: "/var/folders/dn/x3x4wwkd335_rl91by3tqx5w0000gn/T/swift-generated-sources/@_swiftmacro_10FeatureKit15JobCreationViewV12userContexts33_CDDE5BE156468A2E8CC9B6A7E34B1006LL5QueryfMa.swift"
error: the replacement path doesn't exist: "/var/folders/dn/x3x4wwkd335_rl91by3tqx5w0000gn/T/swift-generated-sources/@_swiftmacro_10FeatureKit15JobCreationViewV12userContexts33_CDDE5BE156468A2E8CC9B6A7E34B1006LL5QueryfMa.swift"
error: the replacement path doesn't exist: "/var/folders/dn/x3x4wwkd335_rl91by3tqx5w0000gn/T/swift-generated-sources/@_swiftmacro_10FeatureKit15JobCreationViewV12userContexts33_CDDE5BE156468A2E8CC9B6A7E34B1006LL5QueryfMa.swift"
error: the replacement path doesn't exist: "/var/folders/dn/x3x4wwkd335_rl91by3tqx5w0000gn/T/swift-generated-sources/@_swiftmacro_10FeatureKit15JobCreationViewV12userContexts33_CDDE5BE156468A2E8CC9B6A7E34B1006LL5QueryfMa.swift"
Topic:
App & System Services
SubTopic:
iCloud & Data
Hi,
I am creating (or trying to) my first app using SwiftData - and I have questions :-)
The main question I can't get my head wrapped around is the following:
Let's say I have the sample below...
@Model
class Person {
@Relationship(inverse:\Hat.owner) var hat:Hat
}
@Model
class Hat {
var owner:Person?
}
It looks like I am creating a strong reference cycle between the person and the hat objects? And in fact I am seeing these kinds of reference cycles when I look at the memory debugger.
Many code samples I have seen so far use this type of relationship declaration...
And I am wondering: Am I missing something?
Admittedly I don't find many discussions about memory leaks caused by SwiftData despite the syntax being used in many examples?
So what is the situation? Did Apple just miss to explain that the inverse: declaration causes memory leaks or is there some kind of magic that I should understand?
How do I filter data using @Query with a Set of DateComponents? I successfully saved multiple dates using a MultiDatePicker in AddView.swift. In ListView.swift, I want to retrieve all records for the current or today’s date.
There are hundreds of examples using @Query with strings and dates, but I haven’t found an example of @Query using a Set of DateComponents
Nothing will compile and after hundreds and hundreds of attempts, my hair is turning gray.
Please, please, please help me.
For example, if the current date is Tuesday, March 4 205, then I want to retrieve both records. Since both records contain Tuesday, March 4, then retrieve both records. Sorting works fine because the order by clause uses period which is a Double.
Unfortunately, my syntax is incorrect and I don’t know the correct predicate syntax for @Query and a Set of DateComponents.
Class Planner.swift file
import SwiftUI
import SwiftData
@Model
class Planner {
//var id: UUID = UUID()
var grade: Double = 4.0
var kumi: Double = 4.0
var period: Double = 1.0
var dates: Set<DateComponents> = []
init(
grade: Double = 4.0, kumi: Double = 4.0, period: Double = 1.0, dates: Set<DateComponents> = []
)
{
self.grade = grade
self.kumi = kumi
self.period = period
self.dates = dates
}
}
@Query Model snippet of code does not work
The compile error is to use a Set of DateComponents, not just DateComponents.
@Query(filter: #Predicate<Planner> { $0.dates = DateComponents(calendar: Calendar.current, year: 2025, month: 3, day: 4)},
sort: [SortDescriptor(\Planner.period)])
var planner: [Planner]
ListView.swift image
EditView.swift for record #1
DB Browser for SQLlite: record #1 (March 6, 2025 and March 4, 2025)
[{"isLeapMonth":false,"year":2025,"day":6,"month":3,"calendar":{"identifier":"gregorian","minimumDaysInFirstWeek":1,"current":1,"locale":{"identifier":"en_JP","current":1},"firstWeekday":1,"timeZone":{"identifier":"Asia\/Tokyo"}},"era":1},{"month":3,"year":2025,"day":4,"isLeapMonth":false,"era":1,"calendar":{"locale":{"identifier":"en_JP","current":1},"timeZone":{"identifier":"Asia\/Tokyo"},"current":1,"identifier":"gregorian","firstWeekday":1,"minimumDaysInFirstWeek":1}}]
EditView.swift for record #2
DB Browser for SQLlite: record #2 (March 3, 2025 and March 4, 2025)
[{"calendar":{"minimumDaysInFirstWeek":1,"locale":{"current":1,"identifier":"en_JP"},"timeZone":{"identifier":"Asia\/Tokyo"},"firstWeekday":1,"current":1,"identifier":"gregorian"},"month":3,"day":3,"isLeapMonth":false,"year":2025,"era":1},{"year":2025,"month":3,"era":1,"day":4,"isLeapMonth":false,"calendar":{"identifier":"gregorian","current":1,"firstWeekday":1,"minimumDaysInFirstWeek":1,"timeZone":{"identifier":"Asia\/Tokyo"},"locale":{"current":1,"identifier":"en_JP"}}}]
Any help is greatly appreciated.
So i created an App and for some time it was working fine. The app has features to show pdf to users without logging in. I needed to upload all data to cloudkit on public database.
I was not having knowledge that there are 2 mode being a noob in coding so after i saved all records in development mode in cloudkit when i published my app, i was not able to see them (Reason because live mode works in Production mode).
So i need help now to transfer data from development mode to production mode or any app or code that can help me upload all data in production mode.
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
CloudKit
CloudKit Dashboard
CloudKit Console
My client is using iCloud Mail with his custom domain and he communicated with many govt organizations which seem to all be using Barracuda Email Protection for their spam prevention. I have properly configured his SPF, DKIM & DMARC DNS records however his emails were still being rejected. (Email header below)
I contacted Barracuda support with the email header and they replied saying that the emails were rejected becuase Apple Mail has missing PTR records.
I have sent dozens of emails for testing and looking at all their headers I can see (ms-asmtp-me-k8s.p00.prod.me.com [17.57.154.37]) which does not have a PTR record.
----FULL EMAIL HEADER WITH 3RD PARTY DOMAINS REMOVED-----
<recipient_email_address>: host
d329469a.ess.barracudanetworks.com[209.222.82.255] said: 550 permanent
failure for one or more recipients (recipient_email_address:blocked)
(in reply to end of DATA command)
Reporting-MTA: dns; p00-icloudmta-asmtp-us-west-3a-100-percent-10.p00-icloudmta-asmtp-vip.icloud-mail-production.svc.kube.us-west-3a.k8s.cloud.apple.com
X-Postfix-Queue-ID: 8979C18013F8
X-Postfix-Sender: rfc822; sender_email_address
Arrival-Date: Thu, 20 Mar 2025 12:30:05 +0000 (UTC)
Final-Recipient: rfc822; @******
Original-Recipient: rfc822;recipient_email_address
Action: failed
Status: 5.0.0
Remote-MTA: dns; d329469a.ess.barracudanetworks.com
Diagnostic-Code: smtp; 550 permanent failure for one or more recipients
(recipient_email_address:blocked)
Return-Path: <sender_email_address>
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=sender_domain;
s=sig1; bh=CyUt/U7mIHwXB5OQctPjRH/OxLH7GsLR54JjGuRkj9Y=;
h=From:Message-Id:Content-Type:Mime-Version:Subject:Date:To:x-icloud-hme;
b=hwEbggsctiCRlMlEgovBTjB/0sPRCb2k+1wzHRZ2dZNrZdOqvFSNWU+Aki9Bl8nfv
eEOoXz5qWxO2b2rEBl08lmRQ3hCyroayIn4keBRrgkxL1uu4zMTaDUHyau2vVnzC3h
ZmwQtQxiu7QvTS/Sp8jjJ/niOPSzlfhphqMxnQAZi/jmJGcZPadT8K+7+PhRllVnI+
TElJarN1ORQu+CaPGhEs9/F7AIcjJNemnVg1cude7EUuO9va8ou49oFExWTLt7YSMl
s+88hxxGu3GugD3eBnitzVo7s7/O9qkIbDUjk3w04/p/VOJ+35Mvi+v/zB9brpYwC1
B4dZP+AhwJDYA==
Received: from smtpclient.apple (ms-asmtp-me-k8s.p00.prod.me.com [17.57.154.37])
by p00-icloudmta-asmtp-us-west-3a-100-percent-10.p00-icloudmta-asmtp-vip.icloud-mail-production.svc.kube.us-west-3a.k8s.cloud.apple.com (Postfix) with ESMTPSA id 8979C18013F8;
Thu, 20 Mar 2025 12:30:05 +0000 (UTC)
From: Marcel Brunel <sender_email_address>
Message-Id: <2E8D69EA-FCA6-4F5D-9D42-22A955C073F6@sender_domain>
Content-Type: multipart/alternative;
boundary="Apple-Mail=_F9AC7D29-8520-4B25-9362-950CB20ADEC5"
Mime-Version: 1.0 (Mac OS X Mail 16.0 (3826.400.131.1.6))
Subject: Re: [EXTERNAL] - Re: Brunel - 2024 taxes
Date: Thu, 20 Mar 2025 07:29:27 -0500
In-Reply-To: <SA0PR18MB350300DE7274C018F66EEA24F2D82@SA0PR18MB3503_namprd18_prod_outlook_com>
To: Troy Womack <recipient_email_address>
References: <SA0PR18MB350314D0B88E283C5C8E1BB6F2DE2@SA0PR18MB3503_namprd18_prod_outlook_com>
<9B337A3E-D373-48C5-816F-C1884BDA6F42@sender_domain>
<SA0PR18MB350341A7172E8632D018A910F2D82@SA0PR18MB3503_namprd18_prod_outlook_com>
<SA0PR18MB350300DE7274C018F66EEA24F2D82@SA0PR18MB3503_namprd18_prod_outlook_com>
X-Mailer: Apple Mail (2.3826.400.131.1.6)
X-Proofpoint-ORIG-GUID: uqebp2OIbPqBr3dYsAxdFVkCNbM5Cxyl
X-Proofpoint-GUID: uqebp2OIbPqBr3dYsAxdFVkCNbM5Cxyl
X-Proofpoint-Virus-Version: vendor=baseguard
engine=ICAP:2.0.293,Aquarius:18.0.1093,Hydra:6.0.680,FMLib:17.12.68.34
definitions=2025-03-20_03,2025-03-19_01,2024-11-22_01
X-Proofpoint-Spam-Details: rule=notspam policy=default score=0 bulkscore=0 clxscore=1030
suspectscore=0 mlxlogscore=999 mlxscore=0 phishscore=0 malwarescore=0
spamscore=0 adultscore=0 classifier=spam adjust=0 reason=mlx scancount=1
engine=8.19.0-2411120000 definitions=main-2503200077
Topic:
App & System Services
SubTopic:
iCloud & Data
I'm trying to set up server-to-server authentication with CloudKit Web Services, but keep getting AUTHENTICATION_FAILED errors. I've tried multiple environment settings and debugging approaches without success.
What I've Tried
I created a Swift script to test the connection. Here's the key part that handles the authentication:
// Get current ISO 8601 date
let iso8601Formatter = ISO8601DateFormatter()
iso8601Formatter.formatOptions = [.withInternetDateTime]
let dateString = iso8601Formatter.string(from: Date())
// Create SHA-256 hash of request body
let bodyHash = SHA256.hash(data: bodyData).compactMap { String(format: "%02x", $0) }.joined()
// Get path from URL
let path = request.url?.path ?? "/"
// String to sign
let method = request.httpMethod ?? "POST"
let stringToSign = "\(method):\(path):\(dateString):\(bodyHash)"
// Sign the string with EC private key
let signature = try createSignature(stringToSign: stringToSign)
// Add headers
request.setValue(dateString, forHTTPHeaderField: "X-Apple-CloudKit-Request-ISO8601Date")
request.setValue(KEY_ID, forHTTPHeaderField: "X-Apple-CloudKit-Request-KeyID")
request.setValue(signature, forHTTPHeaderField: "X-Apple-CloudKit-Request-SignatureV1")
}
I've made a request to this endpoint:
What's Happening
I get a 401 status with this response:
"uuid" : "173179e2-c5a5-4393-ab4f-3cec194edd1c",
"serverErrorCode" : "AUTHENTICATION_FAILED",
"reason" : "Authentication failed"
}
What I've Verified
The key validates correctly and generates signatures
The date/time is synchronized with the server
The key ID matches what's in CloudKit Dashboard
I've tried all three environments: development, Development (capital D), and production
The container ID is formatted correctly
Debug Information
My debugging reveals:
The EC key is properly formatted (SEC1 format)
Signature generation works
No time synchronization issues between client and server
All environment tests return the same 401 error
Questions
Has anyone encountered similar issues with CloudKit server-to-server authentication?
Are there specific container permissions needed for server-to-server keys?
Could there be an issue with how the private key is formatted or processed?
Are there any known issues with the CloudKit Web Services API that might cause this?
Any help would be greatly appreciated!
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
CloudKit
Cloud and Local Storage
CloudKit JS
Hi Developer Community,
I'm experiencing a critical issue with CloudKit schema deployment that's blocking my app release. I've been trying to resolve this for several days and would appreciate any assistance from the community or Apple engineers.
Issue Description
I'm unable to deploy my CloudKit schema from development to production environment. When attempting to deploy through the CloudKit Dashboard, I either get an "Internal Error" message or the deployment button is disabled.
Environment Details
App: Reef Trak (Reef aquarium tracking app)
CloudKit Container: ************
Development Environment: Schema fully defined and working correctly
Production Environment: No schema deployed (confirmed in dashboard)
What I've Tried
Using the "Deploy Schema to Production" button in CloudKit Dashboard (results in "Internal Error")
Exporting schema from development and importing to production (fails)
Using CloudKit CLI tools with API token (results in "invalid-scope" errors)
Waiting 24-48 hours between attempts in case of propagation delays
Current Status
App works perfectly in development environment (when run from Xcode)
In TestFlight/sideloaded builds (production environment), the app attempts to fetch records but fails with "Did not find record type: Tank" errors
Log snippet showing the issue:
[2025-03-21] [CloudKit] Schema creation failed: Error saving record <CKRecordID: 0x******; recordName=SchemaSetup_Tank_-**---****, zoneID=_defaultZone:defaultOwner> to server: Cannot create new type Tank in production schema [2025-03-21] [CloudKit] Failed to create schema for Tank after 3 attempts [2025-03-21] [CloudKit] Error creating schema for Tank: Error saving record <CKRecordID: 0x****; recordName=SchemaSetup_Tank_---**-**********, zoneID=_defaultZone:defaultOwner> to server: Cannot create new type Tank in production schema
App Architecture & Critical Impact
My app "Reef Trak" is built around a core data model where the "Tank" entity serves as the foundational element of the entire application architecture. The Tank entity is not just another data type - it's the primary container that establishes the hierarchical relationship for all other entities:
All parameter measurements (pH, temperature, salinity, etc.) are associated with specific tanks
All maintenance tasks and schedules are tank-specific
All livestock (fish, corals, invertebrates) exist within the context of a tank
All user achievements and progress tracking depend on tank-related activities
Without the Tank schema being properly deployed to production, users experience what appears to be a completely empty application, despite successful authentication and CloudKit connection. The app shows "Successfully retrieved iCloud data" but displays no content because:
The Tank record type doesn't exist in production
Without Tanks, all child entities (even if their schemas existed) have no parent to associate with
This creates a cascading failure where no data can be displayed or saved
This issue effectively renders the entire application non-functional in production, despite working flawlessly in development. Users are left with an empty shell of an app that cannot fulfill its core purpose of reef tank management and monitoring.
The inability to deploy the Tank schema to production is therefore not just a minor inconvenience but a complete blocker for the app's release and functionality.
Questions
Is there an alternative method to deploy schema to production that I'm missing?
Could there be an issue with my account permissions or container configuration?
Are there known issues with the CloudKit Dashboard deployment functionality?
What's the recommended approach when the dashboard deployment fails?
I've also submitted a Technical Support Incident, but I'm hoping to get this resolved quickly as it's blocking my App Store release.
Thank you for any assistance!
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags:
CloudKit
CloudKit Dashboard
CloudKit Console
cktool
For a CRM application, I want users to be able to switch between accounts and have their saved contacts stored locally. Whenever a user logs in, the app should fetch data from their specific database location.
What’s the best practice to achieve this?
Should I create a separate database for each user?
Should I store all the data in one database and filter it by user?
Or is there a better approach I should consider?
Is there a way to move user data from UserDefaults to SwiftData when the app is in production so that people don’t lose their data. Currently my audio journals in my journal app has everything in the UserDefaults. Now this is bad for obvious reasons but I was thinking if there was a way. It’s only been 1 week since published and I have already had17 people download it.
Hey guys, I'm developing a Swift app, using iCloud to store some data in Containers, and the new Containers I created are iCloud.com.xxx.dev . Therefore, there is a storage called dev in Settings -> icloud -> Manage Account Storage. Currently, the app is still under development and has not been released to the Appstore.
My question: Settings -> icloud -> Manage Account Storage does not display my app name and icon, but only the suffix of the Containers id. Will this change after it is released to the Appstore? Are there any other control methods? Thank you
I want to get to a point where I can use a small view with a query for my SwiftData model like this:
@Query
private var currentTrainingCycle: [TrainingCycle]
init(/*currentDate: Date*/) {
_currentTrainingCycle = Query(filter: #Predicate<TrainingCycle> {
$0.numberOfDays > 0
// $0.startDate < currentDate && currentDate < $0.endDate
}, sort: \.startDate)
}
The commented code is where I want to go. In this instance, it'd be created as a lazy var in a viewModel to have it stable (and not constantly re-creating the view). Since it was not working, I thought I could check the same view with a query that does not require any dynamic input. In this case, the numberOfDays never changes after instantiation.
But still, each time the app tries to create this view, the app becomes unresponsive, the CPU usage goes at 196%, memory goes way high and the device heats up quickly.
Am I holding it wrong? How can I have a dynamic predicate on a View in SwiftUI with SwiftData?