SRMR SRMR - 5 months ago 154
Swift Question

WatchKit didReceiveApplicationContext not being called

I can't get

didReceiveApplicationContext
to be called. Any ideas?

InterfaceController
:


import WatchKit
import Foundation
import WatchConnectivity

class InterfaceController: WKInterfaceController, WCSessionDelegate {

@IBOutlet var colorLabel: WKInterfaceLabel!

private let session: WCSession? = WCSession.isSupported() ? WCSession.defaultSession() : nil

override init() {
super.init()
session?.delegate = self
session?.activateSession()
}

override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
}

func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]){
let colors : String = applicationContext["color"] as! String
colorLabel.setText(colors)
NSLog("session did receive application context")
}

}


I've been following along with this tutorial: http://www.kristinathai.com/watchos-2-how-to-communicate-between-devices-using-watch-connectivity/

No
NSLog
or setting of the
colorLabel
happens. No idea what I'm missing. Thanks!

Answer

I copied the above code into a new watch app and it works fine. The error must lay on the sending side. Are you certain the code in the iOS app is being called? I presume you are using Xcode and two simulators, one for the iOS app and one for the WatchApp.

The code on the iOS side is not run unless you open the app on the phone simulator. Where and how on the iOS side are you issuing the updateAppContext call?

In my test, this is all that I added to my ViewController.swift on the iOS side (This code will not be triggered until I start the iOS app on my iPhone.)

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let session = WCSession.defaultSession()
    session.delegate = self
    session.activateSession()
    do {
        try session.updateApplicationContext( ["color" : "Red" ])
    } catch _ {

    }
}
Comments