WatchOS 2 app 与 Iphone app 数据交互(四)前台消息数据传输

本文详细介绍了在WatchOS 2中,如何进行前台数据传输,特别是即时消息的发送和接收。通过`sendMessage:`方法发送消息,并使用`replyHandler:`处理回复。当从Apple Watch端发送消息时,可以唤醒iPhone端应用,但反之则无法唤醒。接收到消息时,会触发`session:didReceiveMessage:`方法。此外,还提到了收发大量数据消息的场景,使用`session:didReceiveMessage:replyHandler:`进行处理。

4前台数据传输

前台数据传输只有一种模式,那就是发送即时消息

(1)  发送消息

发送消息函数sendMessage:replyHandler:errorHandler:声明

 

Declaration

SWIFT

funcsendMessage(_message: [String : AnyObject],    replyHandlerreplyHandler:(([String : AnyObject]) -> Void)?,    errorHandlererrorHandler:((NSError) -> Void)?)

OBJECTIVE-C

- (void)sendMessage:(NSDictionary<NSString *

                             id>*)message       replyHandler:(void(^)(NSDictionary<NSString *

                             id>*replyMessage))replyHandler       errorHandler:(void(^)(NSError *error))errorHandler

Parameters

message

A dictionary of property list values thatyou want to send. You define the contents of the dictionary that yourcounterpart supports. This parameter must not benil.

 

replyHandler

A reply handler for receiving a responsefrom the counterpart. Specifynil if you do not want to receive a reply.This block has no return value and takes the following parameter:

replyMessage

A dictionary of property list values containing the response from the counterpart.

 

 

errorHandler

A block that is executed when an erroroccurs. Specifynil if you do not care about error information. This block has no returnvalue and takes the following parameter:

errorHandler

An error object containing the reason for the failure. When sending messages, the most common error is that the paired device was not reachable, but other errors may occur too.

 

 

这是一个异步函数,发送消息到消息队列,不会覆盖之前的消息。

如果需要处理回答消息,则可用replyHandler来处理replyMessage

从watch端调用sendMessage,会唤醒iphone端对应的应用,reachable为真;但是从iphone端调用sendMessage,不能唤醒watch端对应的应用,不改变reachable。所以发送消息时请确保watchiphone时正常连接,且watch打开应用。若果发送消息失败,则调用errorHandler

(2)  接收消息

接收消息时会出发托管session:didReceiveMessage:,声明如下:

optional func session(_ session: WCSession,

   didReceiveMessage message: [String : AnyObject])

OBJECTIVE-C

- (void)session:(WCSession *)session

didReceiveMessage:(NSDictionary<NSString*

                           id> *)message

Parameters

session           

The session object that received themessage from its counterpart.

message        

A dictionary of property list valuesrepresenting the contents of the message. Use the contents of this dictionaryto determine what course of action to take.

上述message就是我们收到的消息,在didReceiveMessage中处理即可。

 

(3)  收发数据消息

上面涉及的是比较短的消息,而watchos2 还可发送内容较多的数据消息,使用方法参照上面的didReceiveMessage,只不过函数改为- session:didReceiveMessage:replyHandler:发数据消息

session:didReceiveMessage:replyHandler:收数据消息

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值