Hi all, I'm working on a really basic counter app as a way to explore SwiftData and have come across some behavior that I don't understand. I have a very simple App Intent that increments a user-specified counter in my app. The intent doesn't throw any errors and correctly updates the CoreData store but, when I switch back to my app from the Shortcuts app (where I'm testing the app intent), the view hasn't updated. Closing and re-opening the app shows the incremented counter value but I'd like to know if it's possible to have my app's UI update when the CoreData store is updated from outside the app without relaunching the whole app.
For some brief context, here's my view and the App Intent:
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var counters: [Counter]
// ...
var body: some View {
NavigationStack {
List {
ForEach(counters) { counter in
CounterRowItem(counter: counter)
}
.onDelete(perform: deleteItems)
}
// ...
}
}
struct IncrementCounterIntent: AppIntent {
static var title: LocalizedStringResource = "Increment Counter"
@Parameter(title: "Name", optionsProvider: CounterOptionsProvider()) var name: String
func perform() async throws -> some IntentResult & ReturnsValue<Int> {
let provider = try CounterProvider()
guard let counter = try provider.fetchCounters().first(where: { $0.name == name }) else {
print("Couldn't find counter with name '\(name)'")
return .result(value: 0)
}
counter.count += 1
try provider.context.save()
return .result(value: counter.count)
}
private final class CounterOptionsProvider: DynamicOptionsProvider {
func results() async throws -> [String] {
try CounterProvider().fetchCounters().map { $0.name }
}
}
}