通过Apple Watch更新app内容的简便方法

时间:2014-11-20 20:26:31

标签: ios nsuserdefaults addobserver watchkit

当我按下AppleWatch App上的按钮时,我无法找到一种简单的方法来更新我的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中,我添加了一个带有此代码的按钮的IBAction:

mySharedDefaults!.setObject("testValue", forKey: "test")
mySharedDefaults!.synchronize()

但是当我按下按钮时,没有任何反应! 如果我在我的iPhone ViewController中设置了一个对象,它可以正常工作,但如果它是通过应用程序更新的话则不行! 有人能帮助我吗?

2 个答案:

答案 0 :(得分:2)

你不幸运,因为在你写问题时,iOS SDK中没有这个API。三天前,2014年12月10日,Apple发布了带有两个的iOS 8.2 beta 2 SDK,这对于这项任务非常重要。

在WatchKit Framework中,WKInterfaceController

// Obj-C
+ (BOOL)openParentApplication:(NSDictionary *)userInfo
                        reply:(void (^)(NSDictionary *replyInfo,
                                        NSError *error))reply

通过调用此方法,iOS将在后台运行您的应用程序,app的appDelegate将收到此消息

- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply. 

这是UIKit Framework中UIApplicationDelegate类在iOS SDK Beta 2(就此问题而言)中添加的第二种方法。

您可以使用NSDictionary和回复块来与Watch app和iOS app进行通信。

示例

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中设置共享应用程序组。 使用containerURLForSecurityApplicationGroupIdentifierNSFileManager类)获取共享组中文件的URL。

如果您想从initWithSuiteName分享偏好NSUserDefaults,那就是您要找的。

答案 1 :(得分:0)

我猜测WatchKit扩展应用程序和您的iPhone应用程序是单独运行的应用程序实例,并且通知是在同一个实例中。

作为替代方案,也许您可​​以在iPhone应用程序的单独线程中进行新操作,定期检查特定键的更改,并在检测到更改时自行生成通知。