Tuesday, February 17, 2015

iOS Share Data Between iOS App and Today Widget (App Extension)


Recently in one of my projects I implemented a Today Widget for the iOS application. While working on that I faced a situation where I have to get data stored in User Defaults of Main app to Today Widget. In this blog I am going to explain how you can sync data between app and widget.  In my case it was simple string data that was stored in user defaults.

For this, first you need to create an app group from Xcode. App group is group of apps which contains main app and an extension. When you create a group from Xcode, it will also create a group in developer portal. For that, first click on project in project explorer and select your main app target in Xcode and go to Capabilities - > App Groups. Initially app groups will be off, first you have to make it on and it will show a pop up window where you can create a new group. Group name always starts with group. prefix. See the image below.

Add your new group like this: group.companyname.groupname and click on Ok. It will sync with developer portal and create app group. Now select your app extension target and go to Capabilities - > App Groups. It will be off first. On it and it will sync with existing app groups which we created in first step. Add your app extension to this group. That's it. Now you can share data between app and app extensions. Now you have to add data by creating group defaults and saving data to groups. See the following code.  This code you can add to your main app.

NSUserDefaults *shared = [[NSUserDefaults alloc]initWithSuiteName:@"group.company.GroupDefaults"];
[shared setObject:[defaults objectForKey:@"key1"] forKey:@"value1"];
[shared setObject:[defaults objectForKey:@"key2"] forKey:@"value2"];
[shared synchronize];

As you can see in above code, we have created NSUserDefaults class instance with suite name or the group. Every time after adding objects to NSUserDefaults, you have to synchronize it. Else data will not be saved. Add following code to your app extension where you want to read data. 

NSUserDefaults *shared = [[NSUserDefaults alloc]initWithSuiteName:@"group.company.GroupDefaults"];
self.value1 = [shared objectForKey:@"key1"];
self.value2 = [shared objectForKey:@"key2"];

Also you can save other data in app extension and can read it in main app. 

[shared setObject:[defaults objectForKey:@"key3"forKey:@"value3"];
[shared setObject:[defaults objectForKey:@"key4"forKey:@"value4"];
[shared synchronize];

As I mentioned above, every time you have to sync after adding or modifying data in user defaults. Hope this will help you.

No comments:

Post a Comment