Display and use Heart Rate with HealthKit on SwiftUI for WatchOS

Display the current heart rate (bpm) on the Apple Watch using the HealthKit framework and SwiftUI.

Luciano Amoroso
SwiftUI
3 min readJan 23, 2020

--

HealthKit is a framework created by Apple for iOS and watchOS to access and use health and fitness data while maintaining the user’s privacy and control. With the HealthKit framework, developers have access to various data from the Apple Watch’s sensors. SwiftUI is an innovative and simple way to build user interfaces across all Apple platforms with the power of Swift.

The problem

Our goal is to implement this framework in an application for WatchOS to fetch the Heart Rate (BPM) in real time and show this data using the new framework SwiftUI.

Step 1: Add HealthKit to the project.

  • Click on the main folder of the project and select extension target.
  • Go to “Signing & Capabilities” tab.
  • Click “+ Capability” and add HealthKit.
  • Modify the info.plist in the Extension folder by adding the Privacy for Health Usage (Record, Share and Update).
  • Import HealthKit in your .swift View

Step 2: Authorize HealthKit on the Watch by sending a notification to the user

Now, let’s see the main function of our project.

The goal of this function is to read the heartbeat data of the user. We are going to configure the heart rate quantity type with the quantityTypeIdentifier and with Predicate and Update we will create a query to receive continuous heart rate samples. The predicate is a filter we apply to our query.

We’re telling our query that we only want data from our Apple Watch device. We created an update handler for accepting results from heart rate query.

In the previous function we call process function to assign lastHeartRate that contains the last bpm value detected from the Watch.

Step 3: The interface part

Now, let’s go to the reference view where we want to display the data obtained from the sensor.

In the first HStack we will insert the heart icon and in the other one we will insert in the Text() the variable it contains bpm value, adjusting the font and the color inserting this as soon as we start the view.

The complete code is available here!

I hope you found this article helpful. If you have any questions, feel free to comment below and I’ll answer it as soon as I can. Thanks!

You can find me on LinkedIn!

--

--

Luciano Amoroso
SwiftUI

iOS Developer @AppleAcademy | Web Developer @Freelance