处理从多个控制器发送和接收的通信的正确方法是什么?
我要做的是从iOS中的两个不同的viewControllers向WatchOS中的两个不同的interfaceControllers发送消息(另外,不是在同一时间)。
以下是我只能用于ViewController2和InterfaceController2之间通信的内容,当从ViewController1向InterfaceController1发送消息时,它会崩溃,因为它似乎始终从InterfaceController2定位EnvironmentVariableTarget.User
方法。
session
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)")
})
}
}
// ===========================================
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
}
}
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)")
})
}
}
由于
答案 0 :(得分:2)
我建议从处理用户界面的控制器中删除所有数据管理。这是一个糟糕的设计,可能会让你头疼,以便混合像这样的层。
您应该拥有一个WCSession
委托的数据管理器,负责保存信息,然后通知相关方(查看控制器等)备份数据已更新。
答案 1 :(得分:0)
根据我所读到的内容,看起来我需要将通信范围缩小到只有一个ViewController和一个InterfaceController,然后通过NSNotification
或Delegation
分享更改。
WatchConnectivity how to share session among multiple WKInterfaceControllers?