I'm building a simple app that persists data using the SwiftData framework with the additional capability of syncing through CloudKit across devices.
All was well until I added a second model object. There's no relationship between the two models, but the simple addition of a new object causes the app to throw an error in the creation of the ModelContainer.
Does anyone have insight on how to correctly do this? Here's some code to illustrate the relevant (I think) parts...
First the main app file...
import SwiftUI
import SwiftData
@main
struct FeederApp: App {
var sharedModelContainer: ModelContainer = {
let feedSchema = Schema([Feed.self])
let noteSchema = Schema([Note.self])
let feedModelConfiguration = ModelConfiguration("default", schema: feedSchema, isStoredInMemoryOnly: false)
let noteModelConfiguration = ModelConfiguration("NoteConfiguration", schema: noteSchema, isStoredInMemoryOnly: false)
do {
return try ModelContainer(for: Feed.self, Note.self, configurations: feedModelConfiguration, noteModelConfiguration)
} catch {
//TODO: add some error correction
fatalError("Could not create ModelContainer: \n\(error)") //ERROR HERE
}
}()
var body: some Scene {
WindowGroup {
ContentView()
.foregroundStyle(.green)
}
.modelContainer(sharedModelContainer)
}
}
and here's the model objects...
import Foundation
import SwiftData
enum Source: String, Codable, CaseIterable, Identifiable, Equatable {
case formula_standard = "Formula"
case formula_enriched = "Formula Enriched"
case breast = "Breast Milk"
var id: Self { self }
}
@Model
final class Feed {
var timestamp: Date = Date.now
var source: Source = Source.breast
var qty_as_int: Int = 0
var id = UUID()
init(timestamp: Date, qty_as_int: Int, source: Source) {
self.timestamp = timestamp
self.source = source
self.qty_as_int = qty_as_int
}
}
and the new model...
import Foundation
import SwiftData
enum WeightType: String, Codable, CaseIterable, Identifiable, Equatable{
case weight = "Standard Weighing"
case birthWeight = "Birth Weight"
var id: Self { self }
}
@Model
final class Weight: Identifiable {
var id = UUID()
var weight: Double
var date: Date = Date()
var type: WeightType = WeightType.weight
init(weight: Double,
type: WeightType) {
self.weight = weight
self.type = type
}
init(weight: Double,
type: WeightType,
date: Date) {
self.weight = weight
self.type = type
self.date = date
}
}
And here's the error:
Feeder/FeederApp.swift:24: Fatal error: Could not create ModelContainer: SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer, _explanation: nil)
Do I need to add the new schema for the new model object manually in the CloudKit dashboard?
If I set the CloudKit database to .none then the app runs but of course doesn't sync the new model object across devices.