Hi there,
Super beginner in Swift and SwiftData here. I created a simple project to import data from a .json file into a Swift model using SwiftData. The process involves loading and decoding the .json file, then saving the data into a model context. However, when I attempt to fetch the data from context, the result is empty. I’ve highlighted the issue within the code.
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var dataItems: [DataItem]
var body: some View {
Button("Import JSON to SwiftData") {
importJSONToSwiftData(context: modelContext)
// some other views
// ....
}
func importJSONToSwiftData(context: ModelContext) {
if let jsonData = loadJSON() {
if let decodedData = decodeJSON(data: jsonData) {
saveToSwiftData(decodedData: decodedData, context: context)
}
}
}
func saveToSwiftData(decodedData: [MyData], context: ModelContext) {
for item in decodedData {
let newData = DataItem(field1: item.field1, field2: item.field2)
// the newData is as expected
context.insert(newData)
}
do {
try context.save() // Persist the changes to SwiftData
// PROBLEM: try to fetch but get nothing
} catch {
print("Failed to save data to SwiftData: \(error)")
}
}
struct MyData: Codable {
let field1: String
let field2: Int
}
@Model
class DataItem: Identifiable {
var id: String
var field1: String
var field2: Int
init(field1: String, field2: Int) {
self.id = UUID().uuidString
self.field1 = field1
self.field2 = field2
}
}
Thanks for any responds.