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.

Screen Shot 2017-02-14 at 1.29.21 PM.png

Go Capabilities and turn on App Groups.

Screen Shot 2017-02-14 at 1.29.50 PM.png

Screen Shot 2017-02-14 at 1.29.54 PM.png

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.

Screen Shot 2017-02-14 at 1.31.31 PM.png

It will also create an entitlements file

Screen Shot 2017-02-14 at 1.31.36 PM.png

Turn on App Groups for your newly created App Extension

Screen Shot 2017-02-14 at 1.32.09 PM.png

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);
}

 Screen Shot 2017-02-14 at 1.33.26 PM.png

Links that help

https://developer.apple.com/library/content/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html#//apple_ref/doc/uid/TP40014214-CH21-SW1

http://www.atomicbird.com/blog/sharing-with-app-extensions

Advertisement