WatchStateModel.swift 964 B

12345678910111213141516171819202122232425262728293031323334353637
  1. import Foundation
  2. import SwiftUI
  3. import WatchConnectivity
  4. class WatchStateModel: NSObject, ObservableObject {
  5. var session: WCSession
  6. @Published var result = ""
  7. init(session: WCSession = .default) {
  8. self.session = session
  9. super.init()
  10. session.delegate = self
  11. session.activate()
  12. }
  13. func addCarbs(_ carbs: Int) {
  14. session.sendMessage(["addCarbs": carbs], replyHandler: nil) { error in
  15. print("ASDF: " + error.localizedDescription)
  16. }
  17. }
  18. }
  19. extension WatchStateModel: WCSessionDelegate {
  20. func session(_: WCSession, activationDidCompleteWith state: WCSessionActivationState, error _: Error?) {
  21. print("ASDF state \(state.rawValue)")
  22. }
  23. func session(_: WCSession, didReceiveMessage message: [String: Any]) {
  24. if let text = message["message"] as? String {
  25. DispatchQueue.main.async {
  26. self.result = text
  27. }
  28. }
  29. }
  30. }