Search code examples
iosobjective-cswiftwatchkitapple-watch

How to call a method defined on the iPhone from the Apple Watch


Is there any way to call a defined method in a class on the iPhone from the Watchkit extension?

From my understanding currently one of the ways to communicate locally between Watch kit and the iPhone is by using NSUserDefaults, but are there other ways?

A simple example would be great.


Solution

  • For WatchOS2 openParentApplication is deprecated. The replacement for it is WCSession in Watch Connectivity Framework

    First, initialize WCSession in both watch(ExtensionDelegate)& iOS(AppDelegate) with following code

    if WCSession.isSupported() {
      let session = WCSession.defaultSession()
      session.delegate = self
      session.activateSession()
    }
    

    Send a notification from watch to Phone using

    session.sendMessage(msg, replyHandler: { (responses) -> Void in
      print(responses)
     }) { (err) -> Void in
     print(err)
    }
    

    Handle the message in AppDelegate using

    func session(_ session: WCSession,
                 didReceiveMessage message: [String : AnyObject],
                 replyHandler replyHandler: ([String : AnyObject]) -> Void)     
    {
       //do something according to the message dictionary
       responseMessage = ["key" : "value"] //values for the replyHandler
       replyHandler(responseMessage)
    }