NSUserDefault change notification handling in watchppExtension

て烟熏妆下的殇ゞ 提交于 2019-11-29 14:08:16

问题


i'm creating a iwatch app just to display a value on watch when clicking on a tableview in iphone app.

i would like to get a notification on a shared userdefault value changes . it is shared between watchkitapp and iphone app, so when the user makes any changes in phone i have to get the notification. i have done the following

When user do Some action in applicaton on phone

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

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 notifications, any one know some solution


回答1:


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.

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.

For filewatcher see code here.

Hope it helps.

Cheers.

Update

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




回答2:


You can try MMWormHole which provides :

  • a channel between the iOS device and the watch which enables you to send data back and forth between them.
  • Also provides a way to do Notifications without having to handle the file monitoring by urself.

Using it ,That will be all the code needed to do notifications in ur app

[self.wormhole passMessageObject:@{@"buttonNumber" : @(1)} identifier:@"button"];

[self.wormhole listenForMessageWithIdentifier:@"button" 
  listener:^(id messageObject) {
    self.numberLabel.text = [messageObject[@"buttonNumber"] stringValue];
}];


来源:https://stackoverflow.com/questions/27794299/nsuserdefault-change-notification-handling-in-watchppextension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!