WatchConnectivity相互通信

在iOS 9.0+和watchOS 2.0+的时候,WatchConnectivity是可以进行手机和手表之间的双向通信的。而在之前,只能有手表主动发起连接,而手机端是无法向手表端发送回执的。

如何双向通信

看一个例子,在这个例子中,手表端点击发送按钮向手机端发送一条消息,消息通过本地通知的方式展现出来。然后,手机向手表发送一个回执。

Watch端
iPhone端

首先需要在手机端和手表端都初始化一个WCSession对象

if([WCSession isSupported])

{

      WCSession *session=[WCSession defaultSession];

      session.delegate=self;

      [session activateSession];

}

前提是先导入WatchConnectivity/WatchConnectivity.h文件并且引用WCSessionDelegate

然后分别在手表端和手机端分别实现代理方法sendMessage:ReplyHandler:方法和didReceiveMessage:ReplyHandler:,其中ReplyHandler方法就是接收完成后发送的回执。

手表端:

if([WCSession defaultSession].isReachable)   

 {        

         NSDictionary *msg=@{@"msg":@"你好iPhone,我是Apple Watch"};       

         [[WCSession defaultSession]sendMessage:msg replyHandler:^(NSDictionary* _Nonnull replyMessage) {

         NSString *reply=replyMessage[@"msg"];

         [self.ResultLabel setText:reply];

         } errorHandler:^(NSError * _Nonnull error) {

         }]; 

}

手机端:

-(void)session:(WCSession *)session didReceiveMessage:(NSDictionary*)message replyHandler:(nonnull void (^)(NSDictionary* _Nonnull))replyHandler

{

   NSString *msg=[NSString stringWithFormat:@"%@",message[@"msg"]];

   UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];

   //需创建一个包含待通知内容的 UNMutableNotificationContent 对象,注意不是    UNNotificationContent ,此对象为不可变对象。

   UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];

   content.title = [NSString localizedUserNotificationStringForKey:@"Hello!" arguments:nil];  

   content.body = [NSString localizedUserNotificationStringForKey:msg

   arguments:nil];

    content.sound = [UNNotificationSound defaultSound];

    // 在 alertTime 后推送本地推送

    UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger

triggerWithTimeInterval:1 repeats:NO];

    UNNotificationRequest* request = [UNNotificationRequest     requestWithIdentifier:@"FiveSecond"

content:content trigger:trigger];

//添加推送成功后的处理!

[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {

    NSDictionary *replyMSG=@{@"msg":[NSString stringWithFormat:@"你好watch,我是       iPhone,你的消息已收到 %@",[NSDate date].description]};

    replyHandler(replyMSG);

    }];

}

这样最简单的相互通信就完成了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 介绍一下iOS10的通知新功能,用户体验的提升和开发者能够发挥的地方非常多,使得iOS更具有竞争力。 1.iOS ...
    F麦子阅读 3,890评论 3 4
  • 218.241.181.202 wxhl60 123456 192.168.10.253 wxhl66 wxhl6...
    CYC666阅读 1,454评论 0 6
  • 许多集成的步骤个推官网都有了,这里只写关于推送的远程推送和本地通知的步骤和代码。APP在后台时:走苹果的APNS通...
    AllureJM阅读 2,772评论 1 9
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,014评论 19 139
  • iOS开发系列--网络开发 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可...
    lichengjin阅读 3,726评论 2 7