查看WCSession,因为有不同的方法可以发送不同类型的数据。这个实现是发送一个字典。
必须WCSession
在手表和手机设备上设置。在 AppDelegate 中didFinishLaunchingWithOptions:
,我在其init
方法中使用 ExtensionDelegate。import WatchConnectivity
使用时请务必WCSession
。如下使用 AppDelegate WCSessionDelegate
。
// AppDelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate, WCSessionDelegate {
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Setup session on phone
if WCSession.isSupported() {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
}
return true
}
// WCSessionDelegate method receiving message from watch and using callback
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
// Reply with a dictionary of information based on the "message"
replyHandler(["Key": "Value"])
}
}
WCSession
手表上的设置:
// ExtensionDelegate.swift
override init() {
let session = WCSession.defaultSession()
session.activateSession()
}
向手机发送包含字典的消息,以便在回调中接收信息:
// GlanceController.swift
WCSession.defaultSession().sendMessage(["Please give Glance data": "Value"], replyHandler:{ (response) in
// Extract data from response dictionary
}) { (error) in
// Handle error
}