问题
I'm trying to share data between an app extension and my container app. I setup an app group in the container app and referenced it my app extension.
When my app extension is accessed, I save an object to NSUserDefaults
//in the app extension
-(void)viewDidLoad {
NSUserDefaults *defaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.mygroup.com"];
[defaults setObject:[NSDate date] forKey:@"Date"];
[defaults synchronize];
}
and in the container app - when it is launched I setup an observer:
// 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");
}
But if my container app was sent to the background, this notification is never called - so I have no way of knowing when the user default was changed.
How can I get the info in the container app (In order to update internally)?
回答1:
I might be mistaken but NSNotification run mainly in the main thread, which means that you will never get that notification.
Also you should unsubscribe to any notification when the view is unloaded, in this case I don't think it's a good idea to have a subscription sitting there.
What I'd do in this case is just check the NSUserDefaults every time the app awakens (there are Delegate methods that you can activate on AppDelegate such as: "applicationDidBecomeActive"
来源:https://stackoverflow.com/questions/25184052/sharing-data-between-app-extension-and-conainer-app