Watch Connectivity is a framework that implements two-way communication between an iOS app and its paired watchOS app. There are several ways to transfer data from an iPhone to watchOS (and back), including CloudKit. From my experience, Watch Connectivity is more robust in some situations because:

  • It doesn’t depend on a network connection
  • There aren’t any problems if the iCloud storage of a user is full
  • It gives more control over data-transfer modes and timing

There are tutorials on Watch Connectivity and sample projects, including one from Apple. It’s a great example but a little bit overwhelming for a beginner.

I created this article to provide a tutorial to get started with Watch Connectivity using a minimal amount of code and SwiftUI for the user interface.

By completing this tutorial, you’ll create an application that:

  • Establishes a connection between watchOS and iPhone
  • Has an indication on whether watchOS is available for receiving messages from the iPhone
  • Can send simple messages from iPhone to watchOS

You can read this guide step by step or download the completed application and figure out how it works yourself.

Getting Started

First, let’s create a new iOS App with Watch App project. Select SwiftUI as the user interface.

A dialogue window showing the user selecting iOS App with With Watch App from the application menu.

Create a new Swift file. In this file, we’ll create a view model that’ll also manage our connection to watchOS.

Dialogue window showing the user creating a view controller.

Import the Watch Connectivity framework to the file.

The model class has to conform to two protocols : NSObject and WCSessionDelegate. To conform to WCSessionDelegate, the class has to implement three methods:

func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?)

func sessionDidBecomeInactive(_ session: WCSession)
func sessionDidDeactivate(_ session: WCSession)

Let’s leave these methods blank at the moment.

Apple suggests that you should start a connectivity session between watchOS and your iPhone as soon as possible because you might want to do some action before your app views load. But we’ll start the session from the ContentView for simplicity.

Create a new object from the ViewModelPhone class in ContentView.

#swiftui #watchos #swift #apple-watch #programming

Get Started With Watch Connectivity With SwiftUI
18.70 GEEK