iOS - WatchKit如何将消息/数据从iPhone应用程序发送到WatchKit应用程序?

问题描述:

我正在创建一个WatchKit应用程序,并想知道如何从iPhone向Watch发送消息/数据?

I am creating a WatchKit app and was wondering how to send a message/data from the iPhone to the Watch?

我知道如何以其他方式做到这一点周围(手表 - >手机)使用' openParentApplication:回复:'和'应用程序:handleWatchKitExtensionRequest:回复:'但无法找到有关如何通过手机进行通信的任何文档观看。

I know how to do it the other way around (watch -> phone) using 'openParentApplication:reply:' and 'application:handleWatchKitExtensionRequest:reply:' but can't find any documentation on how to communicate from phone to watch.

简单的设置是iPhone应用程序有一个按钮,按下时应该更新Watch应用程序上的标签。

Simple setup would be the iPhone app has a button that when pressed should update a label on the Watch app.

有人能指出我正确的方向吗?

Can anyone point me in the right direction?

首先,您必须为目标启用应用程序组:

First, you have to enable app groups for your target:

然后你可以开始通过 NSUserDefaults 写入和读取对象:

Then you can start to write and read objects via NSUserDefaults:

// write 
let sharedDefaults = NSUserDefaults(suiteName: appGroupName)
sharedDefaults?.setInteger(1, forKey: "myIntKey")


// read
let sharedDefaults = NSUserDefaults(suiteName: appGroupName)
let myIntValue = sharedDefaults?.integerForKey("myIntKey")

请参阅与包含iOS应用程序共享数据一章#// apple_ref / doc / uid / TP40014969-CH3-SW1rel =nofollow noreferrer> Apple Watch编程指南:为Apple Watch开发

See the chapter Sharing Data with Your Containing iOS App in Apple Watch Programming Guide: Developing for Apple Watch