我正在尝试在应用扩展和我的容器应用之间共享数据。 我在容器应用程序中设置了一个应用程序组并将其引用为我的应用程序扩展。
当我的应用程序扩展被访问时,我将一个对象保存到 NSUserDefaults
//in the app extension
-(void)viewDidLoad {
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.mygroup.com"];
[defaults setObject:[NSDate date] forKey:@"Date"];
[defaults synchronize];
}
在容器应用程序中——当它启动时我设置了一个观察者:
// in the container app
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDefaultChanged:) name:NSUserDefaultsDidChangeNotification object:nil];
}
-(void)userDefaultChanged:(NSNotification *)note
{
NSLog(@"Changed");
}
但如果我的容器应用程序被发送到后台,则永远不会调用此通知 - 所以我无法知道用户默认值何时更改。
如何获取容器应用程序中的信息(以便在内部更新)?
最佳答案
我可能错了,但 NSNotification 主要在主线程中运行,这意味着您永远不会收到该通知。
此外,当 View 被卸载时,您应该取消订阅任何通知,在这种情况下,我认为在那里订阅不是一个好主意。
在这种情况下,我要做的就是在每次应用程序唤醒时检查 NSUserDefaults(有一些委托(delegate)方法可以在 AppDelegate 上激活,例如:“applicationDidBecomeActive”
关于ios - 在应用程序扩展和容器应用程序之间共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25184052/