【问题标题】:iOS - WatchKit how to send message/data from iPhone app to WatchKit app?iOS - WatchKit 如何将消息/数据从 iPhone 应用程序发送到 WatchKit 应用程序?
【发布时间】:2015-06-13 22:03:18
【问题描述】:
我正在创建一个 WatchKit 应用,并且想知道如何将消息/数据从 iPhone 发送到 Watch?
我知道如何使用 'openParentApplication:reply:' 和 'application:handleWatchKitExtensionRequest:reply:' 反过来(手表 -> 电话)但是找不到任何有关如何从手机与手表进行通信的文档。
简单的设置是 iPhone 应用程序有一个按钮,按下该按钮时应更新 Watch 应用程序上的标签。
谁能指出我正确的方向?
【问题讨论】:
标签:
ios
iphone
swift
communication
watchkit
【解决方案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)
}
“AppShare”是您在为父应用目标创建功能中的应用组时分配的名称。
【解决方案2】:
首先,您必须为您的目标启用应用组:
然后就可以通过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 应用程序共享数据一章
【解决方案3】:
或者,
您甚至可以使用此解决方案在 2 个不同的应用程序之间共享文件,当然也可以在手表应用程序(扩展程序)和父 iOS 应用程序之间共享文件。
第一步由@zisoft 描述,启用应用组。
然后在运行时获取组容器的URL,
- (NSString *)containerPath
{
return [[[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"YOUR_APP_GROUP"] relativePath];
}
现在你可以在给定的路径下写入任何文件/文件夹,下面是我的示例 sn-p,
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");
}
【解决方案4】:
这对我有用。尝试在手表中使用
- (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);
}