I’m using swiftData in my App. When App will be closed, I need to query some data, handle it and save in swiftData. My plan is execute some code in applicationWillTerminate, but report error “failed to find a currently active container for ChartModel “
func applicationWillTerminate(_ application: UIApplication) {
ChartsService.queryAndHandleData()
}
static func queryAndHandleData() {
// modelContext is create referance in a view onAppear
guard self.modelContext != nil else {
return
}
do {
// the error because this line code
var model = ChartModel()
// query some data
let predicate = Account.predicateAllData()
var descriptor = FetchDescriptor(predicate: predicate)
let accounts = try modelContext?.fetch(descriptor)
guard accounts != nil, accounts!.count > 0 else {
return
}
// handle and save data ....
} catch {
print(error)
}
}
I understand the swift container is shut down when applicationWillTerminate function is executed. It would be great if someone could tell me another way.