Mobile Technology

9. TECH: How to Share Data between iPhone and Apple Watch apps

Date Published:

We’ve already taken a look at some of the issues we’ve faced building our Whiskr Apple Watch app in regards to context menus and model dialogs. Next we’re going to look into how we shared data between the iPhone and Apple Watch app. This was probably one of the hardest aspects to learn and get right, and the current documentation isn’t all that great!

To do this we’ll have to create an App Group which is essentially a space which both apps can use. It was brought in with the exetension framework in iOS8 so apps can communicate with their Today widgets, or custom keyboards, and amongst other applications.

Add Capabilities

The first thing we have to do is add the app group capability to both our iPhone and Watch Watch Extension targets.

To do this open up the project settings (blue icon at the top of the list of files) and select the iPhone target. You will need to select the “capabilities” tab at the top of the page and scroll down to turn on app groups.

This requires a connected developer profile, and will take a while to enable. You’ll need to do the same steps to switch on app groups for the watch kit extension also.

Next you need to ensure that the app group string is an identifier string you want and that makes sense for your app, it must start with the word group or it complains. You can also add multiple groups if you wish. Whatever you pick they must be enabled with a blue tick (again this might take a while) and are exactly the same for both the iPhone and Watch extension targets!

ImgurI’ve enabled an app group with the identifier “group.com.calvium.dev.whiskr.defaults”

iPhone NSUserDefaults

Now if we want to write to our app group using NSUserDefaults in the iPhone app we can do the following on our view did load:

//use our group user defaults
NSUserDefaults *defaults = [[NSUserDefaults alloc]  
    initWithSuiteName:@"group.com.calvium.watch.dev.defaults"];

//set a greeting
[defaults setObject:@"hello!" forKey:@"greeting"];

//synchronise
[defaults synchronize];

Watch Extension NSUserDefaults

Next, inside our Watch Extension, inside the first interface controller and the awake with context, we can get the saved defaults:

//use our group user defaults
NSUserDefaults *defaults = [[NSUserDefaults alloc] 
    initWithSuiteName:@"group.com.calvium.watch.dev.defaults"];

//get the greeting    
NSString *greeting = [defaults objectForKey:@"greeting"];

//check if greeting isn't empty
if (greeting) {
    NSLog(@"greeting = %@", greeting);
} else{
    NSLog(@"no user defaults :(");
}

Running

You’ll need to run the iPhone target BEFORE running the Watch Extension to be able to test if your code worked!

Conclusion

Hopefully that helps give you some idea on how to share data between both your apps and build a much better app in the process. Next we’ll be looking at how to make Apple Watch glances work…