我已经为通知中心创建了一个应用程序扩展,它实际上工作正常,除了我无法连续更新它的 UILabel
。我需要这样做的原因是因为我的应用程序有一个不断变化的数据集,我想在扩展中显示它。
我已经尝试使用 NSUserDefaultsDidChangeNotification
来更新扩展中的数据,但它不起作用。这是我的代码:
注册更改通知(扩展)
- (void)viewDidLoad
{
[super viewDidLoad];
...
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(userDefaultsDidChange:)
name:NSUserDefaultsDidChangeNotification
object:nil];
}
- (void)userDefaultsDidChange:(NSNotification *)notification
{
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.company.app"];
//update label
}
向扩展发送数据
- (void)updateData
{
NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.company.app"];
[sharedDefaults setInteger:seconds forKey:@"seconds"];
...
[sharedDefaults synchronize];
}
我在访问同一个组的主应用和扩展中都正确设置了应用组。
有谁知道为什么这不起作用,或者是否有其他方法可以做到这一点? 非常感谢!
最佳答案
我在我的 WatchKit 应用程序中遇到了同样的问题,NSUserDefaultsDidChangeNotification
确实没有在共享 NSUserDefaults
的扩展中被触发。
我找到的最佳解决方案是一个名为 MMWormhole 的库它使用
CFNotificationCenter Darwin Notifications
来实现这一点。
关于ios - 持续更新应用扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26148019/