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:
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:
You can read this guide step by step or download the completed application and figure out how it works yourself.
First, let’s create a new iOS App with Watch App project. Select SwiftUI as the user interface.
Create a new Swift file. In this file, we’ll create a view model that’ll also manage our connection to watchOS.
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