在App Extension和Conainer App之间共享数据 [英] Sharing data between app extension and conainer app

查看:367
本文介绍了在App Extension和Conainer App之间共享数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在应用扩展程序和我的容器应用程序之间共享数据. 我在容器应用中设置了一个应用组,并引用了我的应用扩展名.

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.

访问我的应用扩展程序后,我将一个对象保存到NSUserDefaults

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)?

推荐答案

我可能会误会,但NSNotification主要在主线程中运行,这意味着您将永远不会收到该通知.

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.

在这种情况下,我要做的就是在每次应用唤醒时检查NSUserDefaults(有一些可以在AppDelegate上激活的Delegate方法,例如:"applicationDidBecomeActive"

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"

这篇关于在App Extension和Conainer App之间共享数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆