0

当我按下 AppleWatch 应用程序上的按钮时,我找不到一种简单的方法来更新我的 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 中设置一个对象,它可以工作,但如果它是通过应用程序更新的!有人能帮我吗?

4

2 回答 2

2

您并不幸运,因为当您编写问题时,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. 

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

您可以使用 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( NSFileManagerclass) 获取共享组中文件的 URL。

如果你想分享首选项initWithSuiteNameNSUserDefaults你正在寻找的。

于 2014-12-13T18:30:12.660 回答
0

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

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

于 2014-11-21T05:12:26.467 回答