Apple Watch WCConnectionDelegate,在激活中发送消息偶尔失败吗?



我遇到了一个问题,即通过WCConnection发送消息时,如果在委托方法activationDidCompleteWith中调用,session.sendMessage有时会失败。该问题并非每次都可重复(实际上,它大部分时间都有效)。

但是通过使用我的 UI 中的按钮(调用相同的加载代码)强制session.sendMessage会立即成功进行会话通信,因此我知道问题不在于会话本身或主应用程序。

假设会话已准备好接受activationDidCompleteWith通信是否不安全?有没有更好的地方可以打电话给我的初始通信?

根据我的经验,手表操作系统非常挑剔,尤其是在使用旧型号手表时。话虽如此,我认为问题的答案是:"假设会话已准备好接受激活DidCompleteWith中的通信是否不安全?"是肯定的,假设这是不安全的。

在我自己的应用程序中,我有一个与您的情况非常相似的案例,我通过发送消息直到收到响应来解决它。

// false until a response is received from the phone
let receivedResponse: Bool = false 
// function that sends the message
func requestResponse() {
guard WCSession.default.isReachable else {
print("Phone not reachable")
return
}
// callback that handles response
let responseHandler: ([String: Any]) -> () = { response in
receivedResponse = true
callback(response)
}
WCSession.default.sendMessage(["Request": "Response"],
replyHandler: responseHandler) { error in
print(error.localizedDescription)
}
}
// timer that calls the request function repeatedly
let retryTimer = Timer.scheduledTimer(withTimeInterval: 1,
repeats: true) { timer in
if receivedResponse {
// we know we got a response so clean up timer
timer.invalidate()
}
requestResponse()
}

最新更新