I'm using WatchConnectivity and the WCSessionDelegate to successfully receive user info from my iOS app to my watchOS extension. When new data is received, I want to update my SwiftUI view with the latest information. I have an @ObservedObject property in the HostingController which is set to the latest data when it arrives. However, this does not trigger a UI update. How can I fix this? I've posted the code below. Thank you!
import WatchKit
import SwiftUI
import WatchConnectivity
import Combine
class UserData: ObservableObject {
@Published var account: Account = Account.getCurrentAccount()
}
class HostingController: WKHostingController<ContentView>, WCSessionDelegate {
@ObservedObject private var userData: UserData = UserData()
override init() {
super.init()
if WCSession.isSupported() {
print("WCSession supported")
let session = WCSession.default
session.delegate = self
session.activate()
}
}
override var body: ContentView {
return ContentView(userData: userData)
}
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
}
func session(_ session: WCSession, didReceiveUserInfo userInfo: [String : Any] = [:]) {
guard let accountJSON = userInfo["main-account"] as? String else { return }
let userDefaults = UserDefaults()
userDefaults.set(accountJSON, forKey: "main-account")
self.userData.account = Account.getCurrentAccount()
print("\n\nReceived this: \(accountJSON) \n\n")
}
}