问题描述
我正在创建一个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在应用程序和扩展之间具有distributed notifications
的功能,通知在两者之间均不起作用,而是需要找到一种方式两者都可以监视更改.例如文件.
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
,您可以将文件保留在组文件夹中,并在扩展名中添加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 version
此处.感谢@rivera
添加.
这篇关于watchAppExtension中的NSUserDefault更改通知处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!