Search code examples
ioswatchkitwatchos-2

WatchConnectivity - using sendMessage


I am trying to establish connectivity between the Apple Watch (version 2.0.1) and my iPhone (running iOS 9.1) with the WatchConnectivity API in Swift.

I followed this tutorial and could not achieve messaging between the devices.

Messaging from the Apple Watch:

    let applicationData = ["data":sampleData]

    self.wcSession.sendMessage(applicationData, replyHandler: {(_: [String : AnyObject]) -> Void in
        // handle reply from iPhone app here
        }, errorHandler: {(error ) -> Void in
            // catch any errors here
    })

In my ViewController.swift:

// MARK: - WatchConnectivity Session
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {

    let sample:HKQuantitySample = (message["data"] as? HKQuantitySample)!
    print("Sample messaged: \(sample)")
}

func sessionReachabilityDidChange(session: WCSession) {
    print("session reachability changed: \(session.reachable)")
}

Both Watch app and the iOS app are foreground!! I am not sure what is missing.


Solution

  • All of the WCSession APIs that take a dictionary as a parameter only accept dictionaries of property list types; this includes the sendMessage API you are using:

    message / A dictionary of property list values that you want to send. You define the contents of the dictionary that your counterpart supports. This parameter must not be nil.

    So HKSamples are not a property list type which is why this isn't working, although you are saying the error handler is not getting invoked which sounds very suspicious. Are you certain changing your code to this doesn't log anything?

    self.wcSession.sendMessage(applicationData, replyHandler: {(_: [String : AnyObject]) -> Void in
        // handle reply from iPhone app here
        }, errorHandler: {(error ) -> Void in
            print(error);
    })