5

I have been trying for multiple hours to find a way to send a global variable from the Apple Watch to the iPhone.

There are a lot of questions abut transferring data from iPhone to Apple Watch but not vice versa in Swift 3.

This is not a duplicate because I want to transfer data from the Apple Watch to iPhone, not vice Versa.

How can I do this?

Dylan Murphy
  • 167
  • 1
  • 13
  • 1
    Possible duplicate of [Pass text from iOS label to WatchOS label - swift-](https://stackoverflow.com/questions/44673494/pass-text-from-ios-label-to-watchos-label-swift) – Dávid Pásztor Jun 21 '17 at 16:39
  • How can open open watch app from iPhone with watch connectivity ? – Starman Jan 21 '20 at 07:24

2 Answers2

4

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

For global variable you probably should use updateApplicationContext() of WCSession:

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

On the iPhone you should assign delegate to the default WCSession and activate it. In the WCSessionDelegate, implement the following method:

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

Alternatively you can use sendMessage(_:replyHandler:errorHandler:) but this will require iPhone to be reachable.

In general I would recommend you to follow Zak Kautz advice and read about WatchConnectivity. This is the most common way to communicate between watch and phone.

kelin
  • 11,323
  • 6
  • 67
  • 104
0

Using the watch connectivity framework, you can implement two-way communication.

vashzak
  • 9
  • 1
  • 7