I wrote this simple app to try to fetch and add data to my airport Database in the background.
I'm trying to add some data to the airport table in the background using swift-data, I create a loop that should add and save 100 test airports in a table but when I run the code I only get add 1 airport at the time and the number get add is random, any idea why?
How to use swiftData in the background? So far not so many examples.
actor JsonImporter: ModelActor {
let executor: any ModelExecutor
let context: ModelContext
init(modelContainer: ModelContainer) {
context = ModelContext(modelContainer)
executor = DefaultModelExecutor(context: context)
}
func parseJsonDBAirport() async {
for i in 1...100{
print("loop \(i)")
let airport = Airport(lastPicked: Date(), icao: "test \(i)")
context.insert(airport)
do{
try context.save()
}catch {
print("Error")
}
}
}
}
Using on the view:
struct SettingsView: View {
@Environment (\.modelContext) var mc
var body: some View {
Button {
Task(priority: .background){
let importer = JsonImporter(modelContainer: mc.container)
await importer.parseJsonDBAirport()
}
} label: {
Text("Parse Json airport")
}
NavigationLink {
Airports(dm: dm)
} label: {
HStack{
Image(systemName: "person.2.badge.gearshape.fill")
Text("Airports")
}
}
}
}
my main actor is following:
@main
struct Pilot_VisionApp: App {
var dm = DataManager.shared
var body: some Scene {
WindowGroup {
SettingsView(dm: dm)
}
.modelContainer(for: [UserModel.self, Flight.self, Aircraft.self, CrewModel.self, Airport.self])
}
}
and the airport list as following:
import SwiftUI
import SwiftData
struct Airports: View {
let dm: DataManager
@Query(filter: nil, sort: [SortDescriptor(\Airport.lastPicked)], animation: .default) var airports: [Airport]
var body: some View {
List{
Text("Airport Contains : \(airports.count)")
ForEach(airports) { apt in
Text("icao: \(apt.icao ?? "")")
}
}
}
}
not sure why when I press the button the loop runs correctly I get the printout 100 times but when I open the list of my airport I only see 1 airport saved, every time I press the button one more airport is added to the table but should be 100 airports every time I press the button.
How shuld be use swiftdata in background?
thanks