Contenidos
Crear un proyecto para realizar la comunicación

Crear los siguientes ficheros
ContentView.swift
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import SwiftUI import WatchConnectivity struct ContentView: View { @StateObject var counter = Counter() var labelStyle: some LabelStyle { #if os(watchOS) return IconOnlyLabelStyle() #else return DefaultLabelStyle() #endif } var body: some View { VStack { Text("\(counter.count)") .font(.largeTitle) HStack { Button(action: counter.decrement) { Label("-", systemImage: "minus.circle") } .padding() Button(action: counter.increment) { Label("+", systemImage: "plus.circle.fill") } .padding() } .font(.headline) .labelStyle(labelStyle) } } } |
SessionDelegater.swift
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import Combine import WatchConnectivity class SessionDelegater: NSObject, WCSessionDelegate { let countSubject: PassthroughSubject<Int, Never> init(countSubject: PassthroughSubject<Int, Never>) { self.countSubject = countSubject super.init() } func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { // Protocol comformance only // Not needed for this demo } func session(_ session: WCSession, didReceiveMessage message: [String: Any]) { DispatchQueue.main.async { if let count = message["count"] as? Int { self.countSubject.send(count) } else { print("There was an error") } } } // iOS Protocol comformance // Not needed for this demo otherwise #if os(iOS) func sessionDidBecomeInactive(_ session: WCSession) { print("\(#function): activationState = \(session.activationState.rawValue)") } func sessionDidDeactivate(_ session: WCSession) { // Activate the new session after having switched to a new watch. session.activate() } func sessionWatchStateDidChange(_ session: WCSession) { print("\(#function): activationState = \(session.activationState.rawValue)") } #endif } |
Counter.swift
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import Combine import WatchConnectivity final class Counter: ObservableObject { var session: WCSession let delegate: WCSessionDelegate let subject = PassthroughSubject<Int, Never>() @Published private(set) var count: Int = 0 init(session: WCSession = .default) { self.delegate = SessionDelegater(countSubject: subject) self.session = session self.session.delegate = self.delegate self.session.activate() subject .receive(on: DispatchQueue.main) .assign(to: &$count) } func increment() { count += 1 session.sendMessage(["count": count], replyHandler: nil) { error in print(error.localizedDescription) } } func decrement() { count -= 1 session.sendMessage(["count": count], replyHandler: nil) { error in print(error.localizedDescription) } } } |

