One way would be to perform the import in the background in a @ModelActor. Something like this:
@ModelActor
actor ImportService {
func import(data: [Data]) throws {
for date in data {
let model = Model(/* ... */)
modelContext.insert(model)
}
try modelContext.save()
}
}
This way the import will not block the UI, and the imported data will only be visible in the UI after modelContext.save() is called.
I haven't used SwiftData in a real-world app yet, however, so do be careful. For example I don't know if SwiftData will keep the models in memory until save() is called, so you might have to save more frequently. But even then, the UI will not update for every newly inserted model but only when you choose.
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags: