Many thanks! Here is the skeleton of what I have; any comments? In particular, should I be doing anything in the .backgroundTask(.watchConnectivity)?
import Foundation;
import SwiftUI;
import WatchConnectivity;
@Observable
class Stats
{
var data: [String: Any] = [:];
};
struct StatsView: View
{
@Environment(Stats.self) private var stats;
var body: some View {
VStack {
Text(stats.data.description)
}
}
};
class SessionDelegate: NSObject, WCSessionDelegate
{
private var stats: Stats;
init(stats: Stats)
{
self.stats = stats;
}
func session(_ session: WCSession,
activationDidCompleteWith activationState: WCSessionActivationState,
error: (any Error)?) {
// TODO check state, error, etc.
stats.data = session.receivedApplicationContext;
}
func session(_ session: WCSession,
didReceiveApplicationContext application_context: [String: Any])
{
stats.data = session.receivedApplicationContext;
}
};
@main
struct MyWatchApp: App
{
private var stats: Stats = Stats();
private var session_delegate: SessionDelegate;
init()
{
assert(WCSession.isSupported(), "WCSession is not supported, hmm, when does this happen?");
session_delegate = SessionDelegate(stats: stats);
WCSession.default.delegate = session_delegate;
WCSession.default.activate();
}
var body: some Scene {
WindowGroup {
StatsView()
.environment(stats)
}
.backgroundTask(.watchConnectivity) {
}
}
};