Wednesday, 3 February 2016

Communication between iPhone & Watch OS2

In this tutorial we will cover communication between iPhone and Watch using WatchConnectivity framework (available for Watch OS2 & onwards)

1. Create a Single View Application (you can use other application type too).

2. Click File -> New Target -> WatchKit App (Do not choose WatchKit App for watchOS 1 as it does not support WatchConnectivity framework).

3. So we do have two Targets viz. App and App Watch Extension.

4. Import the WatchConnectivity framework to both the targets.

5. In our App's ViewController.h file
#import <WatchConnectivity/WatchConnectivity.h>
add protocol <WCSessionDelegate>

6. Now in our App's ViewController.h file's viewDidLoad method:
check if WCSession is supported by our iOS, if yes then do initailize WCSession, set its delegate and activate the session as shown:

if ([WCSession isSupported]) {
        WCSession *session = [WCSession defaultSession];
        session.delegate = self;
        [session activateSession];


7. In order to send data to Watch we need to use updateApplicationContext method of WCSession.
NSDictionary containing our data to be passed to Watch can be passed to WCSession.

if ([WCSession isSupported]) {
        WCSession *session = [WCSession defaultSession];
        if (session.isReachable) {
            NSDictionary *applicationDict = [[NSDictionary alloc] initWithObjects:@[@"Value1", @"Value2"] forKeys:@[@"Key1", @"Key2"]];
            [session updateApplicationContext:applicationDict error:nil];


8. Now in App Watch Extension's InterfaceController.h file
#import <WatchConnectivity/WatchConnectivity.h>
add protocol <WCSessionDelegate>

9. To get the data passed from iPhone use WCSession delegate method:

- (void)session:(WCSession *)session didReceiveApplicationContext:(NSDictionary<NSString *, id> *)applicationContext;
applicationContext object is the NSDictionary passed from the iPhone.

Download Code: Here

1 comment: