Apple Watch WCConnectionDelegate,在 activationDidComplete 中发送消息偶尔会失败?

Apple Watch WCConnectionDelegate, sending message in activationDidComplete fails occasionally?

我遇到一个问题,当通过 WCConnection 发送消息时,如果在委托方法 activationDidCompleteWith 中调用 session.sendMessage 有时会失败。这个问题不是每次都能重复(事实上,它在大多数时候都有效)。

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

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

根据我的经验,手表 OS 非常挑剔,尤其是在使用旧型号手表时。话虽这么说,但我认为问题的答案是:"Is it unsafe to assume the session is ready to accept communication in activationDidCompleteWith?" 是肯定的,这样假设是不安全的。

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

    // 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()
    }