Search code examples
iosswiftwatchkitapple-watch

WatchKit - How to get data on first launch?


I created a watch app and I am having problem to send data to the watch the first time it's being open.

I am emphasizing first time because once the app on the watch has been opened, the phone is in charge of updating the app context, hence the phone is always initiating the connection. This part works fine. However the first time the watch app is being opened I want the watch app to initiate the connection and ask the phone app for data. I can't get that to work ...

I've been trying to get the watch to request data from the IOS App by sending a message from the watch using this :

        if (WCSession.defaultSession().reachable) {
            WCSession.defaultSession().sendMessage(infoDictionary,
                replyHandler: { userInfo in
                    self.combinedDict = userInfo
                    self.defaults.setObject(self.combinedDict, forKey: "combinedict")
                    self.defaults.synchronize()
                    self.LoadTheView()
                },
                errorHandler: { (error:NSError) -> Void in
                    print("WatchKit communication error: \(error.localizedDescription)")
            })

Upon reception of the message, the ios app is supposed to reply with a dictionary, I implemented this and I put it in AppDelegate:

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        if #available(iOS 9.0, *) {

            if (WCSession.isSupported()) {
                watchSession = WCSession.defaultSession()
                watchSession!.delegate = self
                watchSession!.activateSession()

            }

        } else {
            // Fallback on earlier versions
        }

        return true

}
      @available(iOS 9.0, *)
        func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {

            print("Did receive message on ios app") // this is never fired

            replyHandler(WatchConnection().SendToWatch()) //WatchConnection().SendToWatch() returns a value of type [String : AnyObject]

        }

However it doesn't work, the app does send the message but never gets a reply ... How can I get that to work ? Is there another way for the watch to request data on first launch ?


Solution

  • WCSession is a process wide singleton and can only have a single delegate. Make sure to set it up in a single spot to avoid confusion or bugs!

    A singleton wrapping WCSession is a decent pattern if you have a lot of different parts of your app that cares about watch connectivity being set up.