您并不幸运,因为当您编写问题时,iOS SDK 中没有用于此的 API。三天前,即 2014 年 12 月 10 日,Apple 发布了 iOS 8.2 beta 2 SDK,其中包含两个对这项任务很重要的方法。
在 WatchKit 框架中,WKInterfaceController 类
// Obj-C
+ (BOOL)openParentApplication:(NSDictionary *)userInfo
reply:(void (^)(NSDictionary *replyInfo,
NSError *error))reply
通过调用此方法,iOS 将在后台运行您的应用,应用的 AppDelegate 将收到此消息
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply.
这是在 UIKit 框架 UIApplicationDelegate 类的 iOS SDK Beta 2(就这个问题而言)中添加的第二种方法。
您可以使用 NSDictionary 和回复块来沟通 Watch 应用和 iOS 应用。
示例
在您的 WKInterfaceController 子类中
- (IBAction)callPhoneAppButtonTapped
{
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"text to display", @"key", nil];
[InterfaceController openParentApplication:dictionary reply:^(NSDictionary *replyInfo, NSError *error) {
NSLog(@"Reply received by Watch app: %@", replyInfo);
}];
}
然后在你的 iOS AppDelegate 类中
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply
{
NSLog(@"Request received by iOS app");
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"your value to return to Apple Watch", @"key", nil];
reply(dictionary);
}
当您点击 Apple Watch 模拟器上的按钮时,您的 iOS 应用程序将在 iOS 模拟器中启动,您应该能够在适当的位置看到 NSLog。
注意
此解决方案适用于在 Watch 和 iOS 应用之间传输对象。
但如果您打算传输更多数据、访问图像、文件等,您应该使用Shared app group。您在 Xcode 项目文件的 Capabilities 中设置共享应用程序组。
使用containerURLForSecurityApplicationGroupIdentifier(NSFileManager 类)获取共享组中文件的 URL。
如果您想从NSUserDefaults 共享首选项initWithSuiteName 就是您要找的。p>