Dear Experts,
I have been looking at thr SimpleWatchConnectivity sample code:
There are a couple of things in there that look out of date. Firstly, it uses a WKApplicationDelegate to receive the background tasks. I believe this can probably be entirely removed, and replaced with .backgroundTask(.watchConnectivity) { ... } on the App. Is that true? What do I need something inside the { ... } there?
Secondly, it is using NSNotificationCenter to send received data from the WCSessionDelegate to the SwiftUI view hierarchy. Is there a better way to do that? I have spent a while trying to work out how a WCSessionDelegate class can connect to a binding to a SwiftUI @State property, and cause the UI to update in response to received data, but I haven't made it work.
Are there any newer examples of how to do this? I'm currently only trying to send some simple applicationContext state from the phone to the watch and have some views update to show the latest values.
Thanks, Phil.
Hi Phil!
That is the latest example. If your goal is to exchange information using applicationContext, probably the most straightforward way to do this is:
- Create an
Observableobject to store that data. - Make your
Observableobject accessible to your WCSessionDelegate and update it when you receive updatedapplicationContextvalues. - Store the
Observableobject in theEnvironment. Something like:
@main
struct MyWatchApp: App {
// You'll have other things here
private var applicationContextModel = ApplicationContextModel()
var body: some Scene {
WindowGroup {
ContentView()
.environment(applicationContextModel)
}
}
}
- Then use it in your view. Something like:
@Environment(ApplicationContextModel.self) private var applicationContextModel
var body: some View {
VStack {
Text("\(applicationContextModel.myValue)")
}
}