Running App in Apple Watch with SwiftUI
For the last three days, I’ve participated in SwiftUI Jam 21 with some friends (here is the link https://swiftuijam.com/), and it was an incredible experience, we have learned a lot and we have a lot of fun. In this Jam we wanted to build an app for the apple watch that tracks your running sessions in SwiftUI.
None of us has any previous experience with AppleWatch development, so it was a great challenge. We had to watch some videos and read a lot about the subject, to be able of building something decent.
Let’s get to the point of how to build this App.
The first thing we need to do is create the app for the Watch. So go to File/New/Target and select in the watchOS tab the following option (Watch App for iOS App)
Easy right? The next step is to authorise the use of HealthKit in the app. So let’s create a WorkoutManager.swift as follow:
And then, you can just call workoutManager.authorizeHealthKit() on your entry point. In my case I did it on WorkoutView as follow
Before running the app, there are two things that you need to do first. The first one is add the HealthKit Capability in the AppleWatch extension.
Then in the info.plist of the AppleWatch extension add information for:
- Privacy — Health Share Usage Description
- Privacy — Health Update Usage Description
- Privacy — Health Records Usage Description
Now you can run the app and you will be able to request permissions in the AppleWatch.
We are set to go to start recording live data from our AppleWatch. To do that, go to the WorkoutManager and do the following (I will explain step by step in the code what is what and how we can use it to build our view)
As you can see, we are recording and saving the data in our Published variables. Now if you create any view and have this WorkoutManager in it, you can have your Hear Rate, Calories Burned and Distance in real time.
Now is your time to create an awesome view and display this data.
More stories like this in