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

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

我知道如何用“ openParentApplication:reply: ”和“ application:handleWatchKitExtensionRequest:reply: ”来绕过(watch – > phone),但是找不到任何有关如何从手机进行通信的文档。

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

任何人都可以指向正确的方向吗?

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

在这里输入图像说明

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

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

请参阅Apple Watch中 包含iOS应用程序的共享数据 编程指南:开发Apple Watch

这对我有用。 尝试在手表中使用

 - (void)registerToNotification { [ self unregisterToNotification ]; CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)(self), didReceivedDarwinNotification, CFSTR("NOTIFICATION_TO_WATCH"), NULL, CFNotificationSuspensionBehaviorDrop); } - (void)unregisterToNotification { CFNotificationCenterRemoveObserver(CFNotificationCenterGetDarwinNotifyCenter(), (__bridge const void *)( self ), CFSTR( "NOTIFICATION_TO_WATCH" ), NULL ); } void didReceivedDarwinNotification() { // your code } 

在主应用程序

 - (void)sendNotificationToWatch:(NSDictionary*)info { CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), CFSTR("NOTIFICATION_TO_WATCH"), (__bridge const void *)(self), nil, TRUE); } 

您应该尝试使用App Groups来共享iOS应用程序和App Extensions之间的数据。

在您的Apple Watch应用程序界面控制器类中:

  let sharedDefaults = NSUserDefaults(suiteName: "group.com.<domain>.<appname>.AppShare") sharedDefaults?.setObject("Came from Apple Watch App", forKey: "AppleWatchData") sharedDefaults?.synchronize() 

在你的父应用程序中:

  let sharedDefaults = NSUserDefaults(suiteName: "group.com.<domain>.<appname>.AppShare") if let appWatchData = sharedDefaults?.objectForKey("AppleWatchData") as? NSString { println(appWatchData) } 

“AppShare”是您在父function目标的Capabilities中创buildApp Group时分配的名称。

或者,

您甚至可以在两个不同的应用程序之间使用此解决scheme共享文件,当然也可以在应用程序(扩展名)和父级iOS应用程

第一步由@zisoft描述,启用应用程序组。

然后在运行时获取组容器的URL,

 - (NSString *)containerPath { return [[[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"YOUR_APP_GROUP"] relativePath]; } 

现在你可以在给定的path上写任何文件/文件夹,下面是我的示例代码片断,

 NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.array]; NSString *path = [[[self containerPath] stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"history"]; if ([data writeToFile:path atomically:YES]) { NSLog(@"Success"); } else { NSLog(@"Failed"); } 

watchOS 2.0有一个名为Watch Connectivity Framework的新框架,可让您在两个设备之间发送消息。

该框架提供了用于在两个进程之间发送文件和数据字典的双向通信通道

请看这里的例子,包括使用debugging模式发送实际字典的例子。

一个WiKi的例子也是可用的 。

祝你好运。

Interesting Posts