您可以使用内置的 WatchConnectivity 框架将消息从 iOS 应用程序发送到配对的 Apple Watch。
1) 首先,在 iOS 应用和 WatchKit 扩展中激活手表连接会话都。在 iOS 端,它可以在应用程序委托的application didFinishLaunchingWithOptions 中完成。在手表方面,您可以在 WatchKit 扩展委托的 applicationDidFinishLaunching 方法中运行此代码。
if WCSession.isSupported() {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
}
2) 现在从您的 iOS 应用发送消息。
let session = WCSession.defaultSession()
session.sendMessage(["message from iOS app":"?"], replyHandler: { reply in
// Handle reply from watch (optional)
}, errorHandler: nil)
3) 通过在 WCSessionDelegate 委托类中实现 session didReceiveMessage 方法在 WatchKit 扩展中接收消息。
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
if let message = message["message from iOS app"] {
NSNotificationCenter.defaultCenter().postNotificationName("myapp.reload", object: self, userInfo: ["data": message])
}
}
在收到来自 iOS 的消息后,我们将使用 postNotificationName 方法发送通知。
4) 在需要更新的 InterfaceController 中订阅此通知(或您希望接收此更新通知的任何其他位置)。
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveReloadNotification:", name: "myapp.reload", object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self,
name: "myapp.reload", object: nil)
}
5) 最后,实现通知处理方法。您可以在此处更新您的 UI。
func didReceiveReloadNotification(notification: NSNotification) {
let userInfo = notification.userInfo as? [String: String]
if let userInfo = userInfo, data = userInfo["data"] {
// Update UI
}
}
注意:为了便于阅读,我使用内联文本字符串作为通知名称“myapp.reload”和消息键“来自 iOS 应用程序的消息”。但在实际应用中,最好为这些文本字符串使用属性以避免拼写错误。