Sharing data between app extension and conainer app

折月煮酒 提交于 2020-01-16 00:42:11

问题


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

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