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。所以发送消息时请确保watch和iphone时正常连接,且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:收数据消息
本文详细介绍了在WatchOS 2中,如何进行前台数据传输,特别是即时消息的发送和接收。通过`sendMessage:`方法发送消息,并使用`replyHandler:`处理回复。当从Apple Watch端发送消息时,可以唤醒iPhone端应用,但反之则无法唤醒。接收到消息时,会触发`session:didReceiveMessage:`方法。此外,还提到了收发大量数据消息的场景,使用`session:didReceiveMessage:replyHandler:`进行处理。
前台消息数据传输&spm=1001.2101.3001.5002&articleId=48596697&d=1&t=3&u=c1443a7e48114cd6816ce182de00443c)
8476

被折叠的 条评论
为什么被折叠?



