ioswatchwatchconnectivity

How can I send a data back to iPhone using WatchConnectivity


I have a Habits app with several counters. Now I figure out how to send a counter's value to iWatch. The question is: when I push a button and change a counter's value on iWatch (for example +1) how can I send the data back to iPhone?


To send a count value from iPhone I have a code in ViewController:

    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { }
  func sessionDidBecomeInactive(_ session: WCSession) { }
  func sessionDidDeactivate(_ session: WCSession) { }

  var session: WCSession?

var count = 0

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    if WCSession.isSupported() {
          session = WCSession.default
          session?.delegate = self
          session?.activate()
      }
}

    @IBAction func addPlusOne(_ sender: UIButton) {
    let count += 1
    let sendHabit = String(count)
    if let validSession = session {
              let iPhoneAppCount = ["Habits": sendHabit]

              do {
                  try validSession.updateApplicationContext(iPhoneAppCount)
              } catch {
                  print("Something went wrong")
              }
          }

To receive the count value to iWatch I have code In InterfaceController:

     let session = WCSession.default

override func awake(withContext context: Any?) {
    super.awake(withContext: context)

       processApplicationContext()
       processApplicationCount()

       session.delegate = self
       session.activate()
}

    func processApplicationCount() {
    if let iPhoneContext = session.receivedApplicationContext as? [String : String] {

        displayLabel.setText(iPhoneContext["Habits"])

    }
}

func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
    DispatchQueue.main.async() {
        self.processApplicationCount()
    }
}

Solution

  • Transferring data from Apple Watch to iPhone is very similar to vice versa.

    For global variables you can use updateApplicationContext() of WCSession from the Watch:

    let session = WCSession.default()
    if session.activationState == .activated {
        session.updateApplicationContext(["my_global": g_myGlobal])
    }
    

    Then on the phone you should assign a delegate to the WCSession and implement the following:

    func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
        let receivedGlobal = applicationContext["my_global"] as? TypeOfTheGlobal
    }