I'm having issues communicating between AppleWatch and iPhone.
iPhone to Watch communication works fine.
Watch to iPhone:
didReceiveApplicationContext
in AppDelegate does not fire!!!
-
I have this in (iPhone) AppDelegate:
import WatchConnectivity
-
if WCSession.isSupported() {
WCSession.default.delegate = self
WCSession.default.activate()
}
...
extension AppDelegate: WCSessionDelegate {
// MARK: WCSessionDelegate
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
//
}
func sessionDidBecomeInactive(_ session: WCSession) {
//
}
func sessionDidDeactivate(_ session: WCSession) {
//
}
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) {
DispatchQueue.main.async {
print("Phone didReceiveApplicationContext")
}
}
}
In a watch InterfaceController I have:
import WatchConnectivity
-
if WCSession.isSupported() {
WCSession.default.delegate = self
WCSession.default.activate()
}
-
extension InterfaceController: WCSessionDelegate {
// MARK: WCSessionDelegate
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
//
}
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) {
DispatchQueue.main.async {
print("Watch didReceiveApplicationContext")
}
}
}
-
I'm trying to communicate by "updating the app context" like so:
@IBAction func buttonPressed() {
guard WCSession.isSupported() else {
return
}
let message = ["buttonPressed" : true]
do {
try WCSession.default.updateApplicationContext(message)
} catch {
print("Something went wrong")
}
}
-
Why doesn't the didReceiveApplicationContext
method fire in AppDelegate?
-
I'm finding that debugging Watch apps is quite complex including the necessity to attach the debugger to the iPhone app etc. ... perhaps there is something simply fundamentally wrong with the way I'm debugging?
This can be closed as a duplicate as I finally found a solution (after lots of trial and error and searching).
I'm unsure what my/the issue is with
WCSession.default.updateApplicationContext
, but the following SO post explains that you can usesendMessage
though you must be careful around thereplyHandler
.If you send the message from the watch using
sendMessage:replyHandler:errorHandler:
, then only that corresponding delegate method (session:message:replyHandler:
) will fire in AppDelegate on the phone. And, you MUST callreplyHandler
!!!WCErrorCodeDeliveryFailed: Payload could not be delivered
So, I'm using
updateApplicationContext
for Phone > Watch, andsendMessage:replyHandler:errorHandler:
for Watch > Phone