WatchOS 5 — Communication between iPhone and Apple Watch and vice versa on Swift — Part 3

This tutorial is written for WatchOS 5, Swift 4.2 and Xcode 10.0 beta (10L176w)

Lito
3 min readJun 19, 2018

What are you going to learn?

  1. Make a little interface for Apple Watch using WKInterfaceTable and managing IBActionsPart 1
  2. Request information from the iPhone application from the Apple Watch with sendMessage(_:replyHandler:errorHandler:)Part 2
  3. Send information from iPhone to Apple Watch sendMessage(_:replyHandler) Part 3
  4. Refactor our code for managing WCSession in one place — Part 4
  5. Update application with updateApplicationContext(_:)Part 5

Send information from iPhone to Apple Watch sendMessage(_:replyHandler)

Today we have the opposite way for communication, iPhone send a message to Apple Watch and the counterpart will not respond, you will see how is similar that to the last tutorial but with different implementation within delegate method.
Well, we can start with implementation from iPhone to the counterpart. As should’ve you know, this is a continuation the other series tutorials, you need to reuse last project.

📱 iPhone implementation

Well, we going to create the logic in our UIViewController. First of all, we create an UIButton that start the sendMessage function and more things that you can following below code:

You need connect IBAction of UIButton with InterfaceBuilder to code 👀..

// 1: Get instance of SessionHandler

// 2: Property for the numbering of sent messages

// 3: Send message to Apple Watch

This is a simple code, and I believe it doesn’t require more explanation.

You can see the InterfaceBuilder aspect in below image:

⌚️ Apple Watch implementation

We only need for to be able to manage received messages implementation with the session(session: didReceiveMessage message:) method and manage our needed logic. Therefore you only add the below method to your InterfaceController class.

Then, we launch the application and attach process, how you can attach it? You can follow this tutorial:

Ok, now that you are able to launch the application, launch it and press multiple times button on iPhone to send a new message and you should watch a similar image:

Conclusion

Congratulations, we have ability to send messages to the counterpart from Apple Watch and from iPhone with sendMessage(_:replyHandler:errorHandler) and sendMessage(_:errorHandler).

Well, if you could notice the delegated methods of WCSession are the same for manage communication in each platform, for that reason in the next tutorial we will go to refactor our code to reuse it on both platforms.

See you soon! Cheers 🍻!!

Collaborate

If you want and you liked the content you can support this writer, thank you very much 😀

--

--

Lito

iOS developer at Kairos DS | iOS Lover | Valencian living on Madrid | Sometimes I try to be a writer