Search code examples
iosobjective-cswiftwatchkitxcode7

Apple Watch Connectivity framework


Previously, before WatchOS 2 it was very hard for your apple watch and iPhone to communicate but with WatchOS 2 and the new Watch Connectivityframework it seems to have improved a lot.

What I am wondering is that with this new framework, is there an easy way for me to run a function on the parent app on the iPhone by clicking a button on the apple watch. Before you would have to use wormhole and it was very confusing.

Basically all I want is to press a button on my watch, and it'll run a line of code on my iPhone!

Any help would be greatly appreciated!


Solution

  • You can use sendMessage API

    1) Call sendMessage method by clicking a button on the apple watch.

    WCSession.defaultSession().sendMessage(applicationDict,
       replyHandler: { ([String : AnyObject]) → Void in
          // Handle reply
       })
       errorHandler: { (NSError) → Void in
          // Handle error
    });
    

    2) didReceiveMessage method is called in your iPhone

    func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
        // send data to Apple Watch
        replyHandler(["retrievedData" : data])
    }
    

    Good luck!