在iOS 9.0+和watchOS 2.0+的時(shí)候,WatchConnectivity是可以進(jìn)行手機(jī)和手表之間的雙向通信的。而在之前,只能有手表主動(dòng)發(fā)起連接丹禀,而手機(jī)端是無(wú)法向手表端發(fā)送回執(zhí)的。
如何雙向通信
看一個(gè)例子鞋怀,在這個(gè)例子中双泪,手表端點(diǎn)擊發(fā)送按鈕向手機(jī)端發(fā)送一條消息,消息通過(guò)本地通知的方式展現(xiàn)出來(lái)密似。然后焙矛,手機(jī)向手表發(fā)送一個(gè)回執(zhí)。
首先需要在手機(jī)端和手表端都初始化一個(gè)WCSession對(duì)象
if([WCSession isSupported])
{
? ? ? WCSession *session=[WCSession defaultSession];
? ? ? session.delegate=self;
? ? ? [session activateSession];
}
前提是先導(dǎo)入WatchConnectivity/WatchConnectivity.h文件并且引用WCSessionDelegate
然后分別在手表端和手機(jī)端分別實(shí)現(xiàn)代理方法sendMessage:ReplyHandler:方法和didReceiveMessage:ReplyHandler:残腌,其中ReplyHandler方法就是接收完成后發(fā)送的回執(zhí)薄扁。
手表端:
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) {
? ? ? ? ?}];?
}
手機(jī)端:
-(void)session:(WCSession *)session didReceiveMessage:(NSDictionary*)message replyHandler:(nonnull void (^)(NSDictionary* _Nonnull))replyHandler
{
? ?NSString *msg=[NSString stringWithFormat:@"%@",message[@"msg"]];
? ?UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
? ?//需創(chuàng)建一個(gè)包含待通知內(nèi)容的 UNMutableNotificationContent 對(duì)象废累,注意不是 ? ?UNNotificationContent ,此對(duì)象為不可變對(duì)象邓梅。
? ?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);
? ? }];
}
這樣最簡(jiǎn)單的相互通信就完成了日缨。