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

时间:2015-04-08 19:07:04

标签: ios iphone swift communication watchkit

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

我知道如何使用“ openParentApplication:回复:”和“应用程序:handleWatchKitExtensionRequest:回复:”反过来(看看 - >手机)但找不到任何关于如何通过手机进行通信的文档。

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

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

5 个答案:

答案 0 :(得分:3)

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

enter image description here

然后您可以通过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 Programming Guide: Developing for Apple Watch

中的与包含iOS应用程序共享数据一章

答案 1 :(得分:2)

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

- (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);
}

答案 2 :(得分:1)

您应该尝试使用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)
    }

&#34; AppShare&#34;是您在父应用目标的功能中创建应用组时指定的名称。

答案 3 :(得分:1)

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

  

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

请参阅示例here,包括sending使用调试模式的实际字典示例。

WiKi示例也是available

祝你好运。

答案 4 :(得分:0)

可替换地,

您可以使用此解决方案在两个不同的应用程序之间共享文件,当然也可以在监视应用程序(扩展程序)和父iOS应用程序之间共享。

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

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

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

现在您可以在给定路径上编写任何文件/文件夹,下面是我的示例代码段,

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");
}