ios - 通过多个 Controller 从 iPhone 向 Watch 发送和接收消息

标签 ios swift watchos watchconnectivity

处理从多个 Controller 发送和接收的通信的正确方法是什么?

我想做的是从 iOS 的两个不同 viewController 向 WatchOS 中的两个不同 interfaceController 发送消息(分开,而不是同时)。

这是我所拥有的,它只适用于 ViewController2 和 InterfaceController2 之间的通信,当消息从 ViewController1 发送到 InterfaceController1 时它会崩溃,因为它似乎一直以 InterfaceController2 的 session 方法为目标.

View Controller 1:

class ViewController1: UIViewController,WCSessionDelegate{
    var session: WCSession!
    override func viewDidLoad() {
      super.viewDidLoad()
        if WCSession.isSupported() {
          session = WCSession.default()
          session.delegate = self
          session.activate()
        }
     }

      func sendDataToWatch(){
        let sendPrice:[String: Double] = ["price": 3.99]
        session.sendMessage(sendPrice, replyHandler: { replyMessage in
            // Some reply here, this could be nil
        }, errorHandler: {error in
            // Catch any errors here, this could be nil
            print("Error: \(error.localizedDescription)")
        })
     }
}

InterfaceController 1:接收来自 ViewController 1 的消息

class InterfaceController1: WKInterfaceController, WCSessionDelegate{
   var session: WCSession!

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        if (WCSession.isSupported()) {
            session = WCSession.default()
            session.delegate = self
            session.activate()
        }
    }

   func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {

    /// Capture data from ViewContorller 2
    let priceFromPhone = message["price"] as? String

    // do something with priceFromPhone
   } 
}

//===========================================

View Controller 2:

class ViewController2: UIViewController,WCSessionDelegate{
    var session: WCSession!
    override func viewDidLoad() {
      super.viewDidLoad()
        if WCSession.isSupported() {
          session = WCSession.default()
          session.delegate = self
          session.activate()
        }
     }

   func sendDataToWatch(){
    let sendEngine:[String: Double] = ["engine": 2.5]
    session.sendMessage(sendEngine, replyHandler: { replyMessage in
        // Some reply here, this could be nil
    }, errorHandler: {error in
        // Catch any errors here, this could be nil
        print("Error: \(error.localizedDescription)")
    })
  }
}

InterfaceController 2: 从 ViewController 2 接收消息

class InterfaceController2: WKInterfaceController, WCSessionDelegate{
   var session: WCSession!

    override func awake(withContext context: Any?) {
        super.awake(withContext: context)

        if (WCSession.isSupported()) {
            session = WCSession.default()
            session.delegate = self
            session.activate()
        }
    }

   func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {

      /// Capture data from ViewContorller 2
      let engineFromPhone = message["engine"] as? String

      // do something with engineFromPhone
    }    
 }

谢谢

最佳答案

我建议从处理 UI 的 Controller 中移除所有数据管理。这是一个糟糕的设计,以后像这样混合图层可能会让你头疼。

您应该有一个数据管理器,它是 WCSession 委托(delegate)并负责保存信息,然后通知相关方( View Controller 等)支持数据已更新。

关于ios - 通过多个 Controller 从 iPhone 向 Watch 发送和接收消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41410600/

相关文章:

ios - 属性文本居中对齐

swift - 在 Picker 中对齐 View

flutter - 是否可以使用 Flutter 来创建 Watch OS 或 Android Wear 的东西?

location - 我可以让 Watch 应用在后台运行吗?

ios - 使用 WatchConnectivity 框架的独立 watch 应用程序

iphone - 使用 block 排队动画

ios - 向 UiTableViewCell 添加删除按钮

ios - 如何将iOS键盘 "go"按钮与UIButton关联?

ios - 如何从父 View 中关闭 SwiftUI NavigationView

ios - WebRTC iOS : Record Remote Audio stream using WebRTC