SRMR SRMR - 10 days ago 5
Swift Question

Watch Connectivity works the first time but not after that

I've tested on the Simulator and Device, somehow Watch Connectivity stops working after it's used once.

I'm passing data from Watch -> iPhone, and it only works once and then stops after that.

Any ideas?

iPhone

ViewController
:

var session: WCSession?

override func viewDidLoad() {
super.viewDidLoad()
if WCSession.isSupported() {
session = WCSession.default()
session?.delegate = self
session?.activate()
}
}

func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
// Received Application Context from Watch
let type = applicationContext["watchType"]
print("Type iPhone: \(type)")

DispatchQueue.main.async {
self.type.text = "Type: \(type)"
}

}


Watch
InterfaceController
:

let session = WCSession.default()

override func awake(withContext context: Any?) {
super.awake(withContext: context)

if WCSession.isSupported() {
session.delegate = self
session.activate()
}
}

@IBAction func startPressed() {
saveEverything()
}

func saveEverything() {
let watchContextType = ["watchType" : "Boxing/Running"]

do {
print("Type Watch: \(watchContextType)")
try session.updateApplicationContext(watchContextType)
} catch {
print("Didn't work")
}
}

Answer

When you use the updateApplicationContext(), you need to change the parameters for each call, otherwise the msg will not be delivered. I belive this is to conserve battery.

Anyway, try sending your message using sendMessage()or sendMessageData(), then the messages get delivered each time, even when they have the same contents. And, they are higher priority than updateApplicationContext so it's win-win :)

Here is the documentation: https://developer.apple.com/library/content/documentation/General/Conceptual/WatchKitProgrammingGuide/SharingData.html#//apple_ref/doc/uid/TP40014969-CH29-SW1