gpt4 book ai didi

ios - 通过 Apple Watch 更新应用程序内容的简便方法

转载 作者:行者123 更新时间:2023-11-28 21:54:32 24 4
gpt4 key购买 nike

当我在 AppleWatch 应用程序上按下按钮时,我找不到一种简单的方法来更新我的 iPhone 应用程序中的 View 。

我像这样使用 NSUserDefaults Observer 进行了尝试:

iPhone 应用程序 View Controller (在 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 中设置一个对象,它会起作用,但如果它是通过应用程序更新的,它就不会起作用!有人可以帮助我吗?

最佳答案

您并不走运,因为当您编写问题时,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 Framework 的 iOS SDK Beta 2(就这个问题而言)中添加的第二个方法,UIApplicationDelegate 类。

您可以使用 NSDictionary 和回复 block 来沟通 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 就是你要找的东西。

关于ios - 通过 Apple Watch 更新应用程序内容的简便方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27048900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com