Reputation: 210
I have an independent watch app which tracks users calories throughout the day.
So when I build and run the app for the first time through Xcode the onAppear(_:)
method of the view is called and the calories are properly retrieved from the HealthKit repository.
Whenever I put my hand down and raise my wrist after 5 min, the applicationDidBecomeActive
of the ExtensionDelegate method is called but the onAppear(_:)
method of the SwiftUI view is not getting called(my HealthKit code to fetch calories is called in this function) and the screen show's the same number of calories the previous time the app ran through Xcode.
Is this expected behaviour? if yes then how can I update my SwiftUI view through the Extension Delegate?
Upvotes: 3
Views: 1534
Reputation: 352
I think the failure to invoke .onAppear on wrist-raise is a bug, and I filed feedback about it. In the meantime, I got this to work as a "wrist-raise" event.
// ExtensionDelegate.swift
extension Notification.Name {
static var applicationIsActive: Notification.Name {
Notification.Name("applicationIsActive")
}
}
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidBecomeActive() {
NotificationCenter.default.post(name: .applicationIsActive, object: nil)
}
}
// ContentView.swift
private var isActive = NotificationCenter.default.publisher(for: .applicationIsActive)
.onReceive(isActive) {_ in self.viewModel.refresh()}
Upvotes: 2