WCSessionには、さまざまな種類のデータを送信するさまざまな方法があります。この実装は辞書を送信しています。
時計と電話機の両方にWCSession
を設定する必要があります。 AppDelegateをdidFinishLaunchingWithOptions:
にして、私はそのinit
メソッドでExtensionDelegateを使用します。 WCSession
を使用する場合は必ずimport WatchConnectivity
にしてください。以下のように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
}