通过Apple Watch更新应用程序内容的简单方法
当我按下AppleWatch应用程序上的button时,我无法find更新iPhone应用程序中的视图的简单方法。
我用NSUserDefaults Observer像这样试了一下:
iPhone App ViewController(在ViewDidLoad()中):
// Create and share access to an NSUserDefaults object. mySharedDefaults = NSUserDefaults(suiteName: "group.sharedTest") //Add Observer NSUserDefaults.standardUserDefaults().addObserver(self, forKeyPath: "test", options: NSKeyValueObservingOptions.New, context: nil)
在Watchkit Extensions InterfaceController中,我添加了一个带有这个代码的button的IBAction:
mySharedDefaults!.setObject("testValue", forKey: "test") mySharedDefaults!.synchronize()
但是当我按下button,没有任何反应! 如果我在我的iPhone视图控制器中设置一个对象,它的工作,但不是如果它通过应用程序更新! 有人能帮我吗?
你没有幸运,因为当你写下你的问题时,在iOS SDK中没有这个API。 三天前,2014年12月10日苹果公司发布了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.
这是iOS SDK Beta 2(在这个问题上)在UIKit Framework中添加的第二种方法, UIApplicationDelegate
类。
您可以使用NSDictionary和回复块来沟通观看应用程序和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模拟器上的button时,iOS模拟器中的iOS应用程序将启动,您应该能够看到NSLog的正确位置。
注意
此解决scheme适用于在Watch和iOS应用程序之间传输对象。 但是,如果您计划传输更多数据,访问图像,文件等,则应使用Shared app group
。 您在Xcode项目文件中的Capabilities中设置共享应用程序组。 使用containerURLForSecurityApplicationGroupIdentifier
( NSFileManager
类)来获取URL到共享组中的文件。
如果你想共享NSUserDefaults
Preferences initWithSuiteName
就是你正在寻找的。
我猜测,WatchKit扩展应用程序和你的iPhone应用程序是独立运行的应用程序实例,并且通知是在同一个实例中。
或者,也许您可以在iPhone应用程序的单独线程中进行新的操作,该应用程序会定期检查特定键的更改,并在检测到更改时自行生成通知。