watchAppExtension 中的 NSUserDefault 更改通知处理 [英] NSUserDefault change notification handling in watchAppExtension

查看:36
本文介绍了watchAppExtension 中的 NSUserDefault 更改通知处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个  Watch 应用,只是为了在用户点击 iPhone/主机应用中的表格视图时在手表上显示一个值.

I'm creating a  Watch app just to display a value on the watch when the user taps on a table view in the iPhone/host app.

我想收到共享 UserDefault 值更改的通知.它在 WatchKit 应用程序和 iOS(主机)应用程序之间共享,因此当用户在主机应用程序中进行任何更改时,我希望收到通知.我已完成以下操作:

I would like to get a notification the value changes on a shared UserDefault. It is shared between WatchKit app and the iOS (host) app, so when the user makes any changes in the host app I'm expecting to get the notification. I've done the following:

当用户在应用程序(宿主应用程序)中执行某些操作时:

When user do some action in application (host app):

NSUserDefaults *shared = [[NSUserDefaults alloc] initWithSuiteName:@"group.app"];
id object = [self.plantsArray objectAtIndex:[self.plantsTable indexPathForSelectedRow].row];
[shared setObject:object forKey:@"data"];
[shared synchronize];

在 Watchkit 扩展中已经注册了通知:

In the Watchkit extension have registered for the notification:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(print) name:NSUserDefaultsDidChangeNotification object:nil];

但不幸的是我没有收到任何通知,有人有解决方案吗?

but unfortunately I'm not getting any notification, has anyone a solution?

推荐答案

我认为 iOS 没有应用和扩展之间分布式通知的能力,通知在两者之间不起作用,而是你需要找到一种方法,两者都可以监控变化.例如文件.

I don't think iOS has capability of distributed notifications between app and extension, notifications will not work between both, instead you need to find a way in which both can monitor changes. For example files.

因为你已经创建了group,你可以在group文件夹中保留一个文件并在扩展名中添加一个filewatcher,从app更新文件,然后filewatcher 会捕捉到变化,你的工作就完成了.

As you already have created group, you can keep a file in the group folder and add a filewatcher in extension, update the file from app, and filewatcher will catch the change, and your work is done.

对于 filewatcher,请参阅代码此处.

希望有帮助.

干杯.

更新

此处查找File watcher Swift 版本.感谢 @rivera 添加.

Find File watcher Swift version here. Thanks @rivera for adding.

这篇关于watchAppExtension 中的 NSUserDefault 更改通知处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆