I wanted to get my SwiftData previews working in my primary project, so I started modeling them after the SampleTrips project.
After messing around with that & being unable to make it work, I brought the same (working) sample code into my main project, unfortunately that's not working...
I've attached the preview error (note, there's nothing in the Diagnostic Reports).
//Sample code that works in it's own project, but not my primary target.
import SwiftUI
import SwiftData
struct TestSwiftDataStuffView: View {
let trip: Trip
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, \(trip.name)!")
.padding()
.foregroundColor(.red)
}
.padding()
}
}
#Preview(traits: .sampleDataSecondary) {
@Previewable @Query var trips: [Trip]
TestSwiftDataStuffView(trip: trips.first!)
}
actor DataModelSecondary {
struct TransactionAuthor {
static let widget = "widget"
}
static let shared = DataModelSecondary()
private init() {}
nonisolated lazy var modelContainer: ModelContainer = {
let modelContainer: ModelContainer
let schema = Schema([
Trip.self
])
do {
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false, cloudKitDatabase: .none)
modelContainer = try ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Failed to create the model container: \(error)")
}
return modelContainer
}()
}
@Model class Trip {
@Attribute(.preserveValueOnDeletion)
var name: String
init(name: String) {
self.name = name
}
}
extension Trip {
static var previewTrips: [Trip] {
[
Trip(name: "Revenant"),
Trip(name: "Newcastle"),
Trip(name: "Bianca")
]
}
}
struct SampleDataSecondary: PreviewModifier {
static func makeSharedContext() throws -> ModelContainer {
let config = ModelConfiguration(isStoredInMemoryOnly: true)
let container = try ModelContainer(
for: Trip.self,
configurations: config
)
SampleDataSecondary.createSampleData(into: container.mainContext)
return container
}
func body(content: Content, context: ModelContainer) -> some View {
content.modelContainer(context)
}
static func createSampleData(into modelContext: ModelContext) {
Task { @MainActor in
let sampleDataTrips: [Trip] = Trip.previewTrips
let sampleData: [any PersistentModel] = sampleDataTrips //+ sampleDataLA + sampleDataBLT
sampleData.forEach {
modelContext.insert($0)
}
try? modelContext.save()
}
}
}
@available(iOS 18.0, *)
extension PreviewTrait where T == Preview.ViewTraits {
@MainActor static var sampleDataSecondary: Self = .modifier(SampleDataSecondary())
}