简体   繁体   中英

send message from AppleWatch to iPhone app using watchOS2

I tried to send message to iPhone app from iwatchExtension(on ButtonClick) using WCSession method like

[[WCSession defaultSession] sendMessage:applicationData
                                   replyHandler:^(NSDictionary *reply)

But delegate method - (void)session:(WCSession *)session didReceiveMessage: is not getting called.

when I tried same while passing data from iPhone to iWatch, it works properly. All delegate methods get called properly in "Extension Delegate" class.

If you check the definition of WCSession delegate methods you will find a minor difference about their receiving nature. Check the bold quote.

/** Called on the delegate of the receiver. Will be called on startup if the incoming message caused the receiver to launch. */
- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary *)message;

/** Called on the delegate of the receiver when the sender sends a message that expects a reply . Will be called on startup if the incoming message caused the receiver to launch. */
- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary *)message replyHandler:(void(^)(NSDictionary *replyMessage))replyHandler;

As you are providing a non-null parameter for replyHandler: , you should be receiving the message in other delegate ie -(void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message .

You are using [WCSession defaultSession] sendMessage: ...] for communication, which lacks the delegate assignment plus you have not activated the session.

In your Extention class, create an ivar for WCSession and write this code

- (void)awakeWithContext:(id)context {
    [super awakeWithContext:context];
    // Configure interface objects here.    
    if([WCSession isSupported])
    {
        session = [WCSession defaultSession];
        session.delegate = self;
        [session activateSession];
    }    
}

and then send message like [session sendMessage:applicationData replyHandler:^(NSDictionary *reply) .

In your AppDelegate.m file just create and instance of WCSession and activate it and use the correct delegate method to capture the message.

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

I believe this should solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM