I think I finally figgured it out!
This Thread discusses a similar issue, it seems to be a SwiftUI bug. When the App launches in the background from being inactive, it’s crashing when an @Environment variable is used in the root ContentView (only seems to happen for .modelContext for me).
I was able to reliably reproduce it by launching the App in the background directly.
This is what I was doing:
@main
struct MyApp: App {
var sharedModelContainer: ModelContainer = {
// ...
}()
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(sharedModelContainer)
}
}
struct ContentView: View {
@Environment(\.modelContext) var modelContext
var body: some View {
MyView()
}
func someFunc() {
modelContext.insert(...)
}
}
I’m now passing the container to the root view as an argument and adding it there via .modelContainer(...), which seems to have fixed the issue:
@main
struct MyApp: App {
var sharedModelContainer: ModelContainer = {
// ...
}()
var body: some Scene {
WindowGroup {
ContentView(container: sharedModelContainer)
}
}
}
struct ContentView: View {
let container: ModelContainer
var body: some View {
MyView()
.modelContainer(container)
}
func someFunc() {
let modelContext = ModelContext(container)
modelContext.insert(...)
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: