How to share data between App Extension and Host
Since app extensions run as part of a host application rather than their containing app (i.e. your app extension runs in somebody elses app), data sharing isn’t automatic.
App extensions and hosts can share data via App Groups. App Groups are shared containers both App Extensions and Hosts can use to communicate with each other since no direct communication is allowed.
Setting up an App Group
App Groups are the scheme iOS uses to allow different apps to share data. If you have the right entitlements and proper provisioning, they can access a shared directory outside their normal iOS sandbox.
Create a new SingleView app.
Go Capabilities and turn on App Groups.
Now you can share data like this.
@implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSUserDefaults *myDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.spike.AppGroupNSUserDefaults"]; [myDefaults setObject:@"foo" forKey:@"bar"]; NSLog(@"\n\nWrote it!\n\n\n"); }
Add an App Extension
Now let’s add an app extension and try this out. New Target -> iMessage Extension.
Note: This will automatically setup a sub bundle id that should work for you out of the box. Bundle ids are important and this must be nested.
It will also create an entitlements file
Turn on App Groups for your newly created App Extension
And now try reading something from NSUserDefaults written by your container app.
- (void)viewDidLoad { [super viewDidLoad]; NSUserDefaults *myDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.spike.AppGroupNSUserDefaults"]; NSString *value = [myDefaults objectForKey:@"bar"]; NSLog(@"\n\n\nvalue: %@\n\n\n", value); }
Links that help
Leave a Reply