how can I use WCSessionUserInfoTransfer in watchos?

1.2k views Asked by At

is anywhere a simple tutorial, how I can use the WCSessionUserInfoTransfer to change data between my watch and iOS ?

And what must be written in the delegate of the iOS -App?

in my old programming I used:

[WKInterfaceController openParentApplication:@{@"Kommando":@"Radius"} reply:^(NSDictionary *replyInfo, NSError *error) {
        if (error) {
            NSLog(@"Error from parent: %@", error);
        } else {
            NSLog(@"Radius from parent: %@", [replyInfo objectForKey:@"Radius"]);
        }
    }];
1

There are 1 answers

1
Kristina On

The first thing you need to do is to define a WCSession. This must be defined and activated in every class that you're planning on transferring data to and receiving data from. To use WCSession, make sure it's supported, and then activate the default session as shown below.

#import <WatchConnectivity/WatchConnectivity.h>

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

From here, you can use transferUserInfo where ever you need to send data (from the watch or the iOS app):

[[WCSession defaultSession] transferUserInfo:@{@"Kommando":@"Radius"}];

On the receiving end, you would use session:didReceiveUserInfo. Note that this does NOT need to be in the app delegate anymore on the iOS app side, unlike handleWatchKitExtensionRequest. You can use this where ever you need to receive the data. Make sure to activate WCSession, as shown above, in the class where you have didReceiveUserInfo also.

- (void)session:(nonnull WCSession *)session didReceiveUserInfo:(nonnull NSDictionary<NSString *,id> *)userInfo {
    NSLog(@"Radius from parent: %@", [userInfo objectForKey:@"Radius"]);
}