watchkit , iOS sending data between watch and ipho

2019-04-17 08:56发布

I want to create one button in watch and while tapping on watch start one process to my ios app. How can I send the data between 2 devices

-(void)viewWillAppear:(BOOL)animated

{
 [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(sayHello:) name: @"sayHelloNotification" object: nil];

}

plus

 [[NSNotificationCenter defaultCenter] postNotificationName: @"sayHelloNotification" object: nil];

in my button watch but it doesn't work

7条回答
Luminary・发光体
2楼-- · 2019-04-17 09:47

Starting from watchOS 2.0 you could just send a message between two devices. You could send a message Watch->iPhone at any time (event if your iPhone counterpart isn't running) and iPhone->Watch if your watch counterpart is presenting. Just check [WCSession defaultSession].isReachable to be sure you could send a message.

For both platform here's code example:

@import WatchConnectivity;

...

if ([WCSession defaultSession].isReachable) {
     [[WCSession defaultSession] sendMessage:@{
                                   @"Key" : @"Value"
                              } replyHandler:^(NSDictionary<NSString *,id> * _Nonnull replyMessage) {
                                   NSLog(@"Sent update is OK");
                              } errorHandler:^(NSError * _Nonnull error) {
                                   NSLog(@"Sent update with error %@", error);
                              }];
}

To react on this message you should implement in counterpart WCSessionDelegate:

- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message;

or

- (void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *, id> *)message replyHandler:(void(^)(NSDictionary<NSString *, id> *replyMessage))replyHandler;
查看更多
登录 后发表回答