あなたは内蔵を使用することができますWatchConnectivity枠組みの中でペアアップルウォッチにiOSアプリからメッセージを送信します。
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拡張のメッセージを受信します。我々はpostNotificationName
方法で通知を送信しているのiOSからメッセージを受信すると
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])
}
}
。
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
}
}
注:読みやすさのために、私は、「iOSアプリからのメッセージ」の通知名「myapp.reload」とメッセージキーのインラインテキスト文字列を使用しています。しかし、実際のアプリでは、これらのテキスト文字列にプロパティを使用して、誤植を避ける方がよいでしょう。
グレートアンサー!しかし、これは「サポートされています」と記載されていないと付け加えたいと思います。これは将来的には防止されるかもしれませんし、ウォッチキットのアプリケーションを受け入れる際にリンゴ認証に合格しないかもしれません。しかし、今のところそれは素晴らしい作品です! –