是否可以从我的应用程序向我的watchOS扩展程序发送消息,以便我ex可以更新我的watch UI?
我正在使用WKInterfaceController.openParentApplication
将信息从手表扩展发送到应用程序。但我该如何做相反的事情——从应用程序到手表扩展?
如果您正在为watchOS2开发,则可以使用WatchConnectivity。这为您提供了多种在手表和iPhone之间来回传输数据的选项。
如果您想从手表向iPhone发送消息(当两者都处于活动状态时),请使用交互式消息。阅读有关WatchConnectivity的更多信息,了解发送数据的不同方式。我将给您举一个简短的代码示例。
您需要在watch和iOS上扩展WCSessionDelegate。
if (WCSession.isSupported()) {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
}
if (WCSession.defaultSession().reachable) {
//This means the companion app is reachable
}
在你的监督下,这将发送数据。
let data = //This is the data you will send
WCSession.defaultSession().sendMessage(data,
replyHandler: { ([String : AnyObject]) → Void in
})
errorHandler: { (NSError) → Void in
});
并在您的iPhone上接收数据实现委托方法:
func session(_ session: WCSession,
didReceiveMessage message: [String : AnyObject])
观看操作系统4+
更新@Philip在设置会话后需要做的回答
您需要使用replyHandler方法将数据从iPhone获取到WatchOS应用程序扩展,如
WCSession.default.sendMessageData(Data(), replyHandler: { (data) in
let deviceId = String(data: data, encoding: .utf8)
print("DEVICE ID : (deviceId)")
DataModel.shared.deviceId = deviceId
}, errorHandler: nil)
这将根据您的要求从Watch App Extension调用。
在主应用程序代理中,您需要实现WatchKit会话代理
// WATCH OS MESSAGE RECIEVE WITH REPLY HANDLER
func session(_ session: WCSession, didReceiveMessageData messageData: Data, replyHandler: @escaping (Data) -> Void) {
print("SESSION MESSSAGE DATA: (messageData)")
if let deviceId = UIDevice.current.identifierForVendor?.uuidString,
let data = deviceId.data(using: .utf8) {
print("REPLY HANDLER MESSSAGE DATA: (data)")
replyHandler(data)
}
}
在replyHandler
中,您可以以Data
格式传递信息。