import Foundation import WatchConnectivity @MainActor final class WatchConnectivityService: NSObject, WCSessionDelegate { static let shared = WatchConnectivityService() private let store: WatchProfileStore private var handlers: [String: WatchDataHandling] = [:] private override init() { self.store = .shared super.init() registerDefaultHandlers() activateIfSupported() loadCurrentContext() } private func registerDefaultHandlers() { let profileHandler = UserProfileWatchHandler(store: store) registerHandler(profileHandler) } func registerHandler(_ handler: WatchDataHandling) { handlers[handler.key] = handler } private func activateIfSupported() { guard WCSession.isSupported() else { store.setStatus("WatchConnectivity not supported") return } let session = WCSession.default session.delegate = self session.activate() } private func loadCurrentContext() { guard WCSession.isSupported() else { return } handleContext(WCSession.default.applicationContext) } private func handleContext(_ context: [String: Any]) { for (key, handler) in handlers { guard let data = context[key] as? Data else { continue } handler.handle(data: data) } } func session( _ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error? ) { loadCurrentContext() } func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) { handleContext(applicationContext) } }