Saving SwiftData in Background Does Not Update @Query

I'm trying to use SwiftData for a new app after ~20 years of Core Data (and EOF before that). So while I'm new to SwiftData, I'm not new to Apple persistence frameworks.

I've got a pretty typical workflow - need to load some JSON from the network, convert that into model objects.

I've created an actor using the @ModelActor macro and I'm using that to do the network fetch and insert. I can set breakpoints in this code and see that it does indeed run and it's running on a non-main queue. That all seems fine.

The problem is that my @Query powered variable in my SwiftUI user interface does not get updated when this data is loaded and saved as I would expect it to.

I'm passing in the container to the actor using modelContext.container from the same modelContext that is powering the view / in the environment. My understanding was that like Core Data before it, the SwiftData framework was listening for the relevant notifications passed by the container/context, processing those and updating the UI but I can only see my data if I quit and relaunch the app.

This seems like it should be a very common use case but I've not found much online. Not sure if that means I'm just doing something fundamentally wrong or what.

Tested on both iOS 18 and 17 with the same results.

Anyone else doing this successfully? What could I be doing wrong?

The best way I've seen online is to hook into the ScenePhase & to iterate over your data:

///struct <YourApp>: App {...
.onChange(of: scenePhase) { _, newValue in
            if case .active = newValue {
                items.forEach { $0.title = $0.title }
            }
        }

//Or do something like the following:
modelContainer = DataModel.shared.modelContainer

I don't think we're allowed to link out here, but lookup "Widget-Intermediate-Animation" on GitHub for more info & the new SwiftData History stuff.

When using Shortcuts/App Intents, I've yet to find a good way to update the main UI (The data is being manipulated, but the UI isn't redrawing)... I've been using the above which works when navigating out/into a NavStack view or backgrounding & re-foregrounding the app.

Ie, less than ideal, but we do what we gotta do! 😅

Saving SwiftData in Background Does Not Update @Query
 
 
Q