HealthKit Basics in Swift

Mehmet Ateş
IBTech
Published in
5 min readMar 11, 2023

Greetings again everyone. After a short break, it is back with a fun article.

Health problems are very popular nowadays. And developing technologies are trying to support us in this regard. Apple has also not left its ecosystem incomplete in this regard. With the module called HealthKit they have developed, we can use the sensors on the iPhone — iWatch and make health assessments. Let’s learn the basics of this kit.

Before we begin, we have a topic about personal data security, which is one of the things Apple does best. We need to get permission from the user by stating that we need some data.

There are a few simple steps you need to take to do this. After that, everything is very easy.

The first step is to add healthkit under the Signing & Capabilities menu.

Then adding these 3 values ​​to the info plist and giving your message to the user.

After that it ends in code. We get this screen with the code block below.

struct HealthKitView: View {
var healthStore: HKHealthStore = HKHealthStore()

init() {
request()
}

private func request() {
let typesToRead: Set<HKObjectType> = [HKObjectType.quantityType(forIdentifier: .stepCount)!, HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!, HKObjectType.quantityType(forIdentifier: .heartRate)!]

let typesToWrite: Set<HKSampleType> = [HKObjectType.quantityType(forIdentifier: .stepCount)!, HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!]

healthStore.requestAuthorization(toShare: typesToWrite, read: typesToRead) { (success, error) in
if success {
// Success
} else {
// Error handle
}
}
}
}

We got our permissions. Now let’s explore some of the healthKit capabilities.

  • Tracking Physical Activity

One of the most popular uses for HealthKit is tracking physical activity. HealthKit can monitor your steps, distance, and even your workouts. This data can be used to help you set goals and track your progress. You can also use third-party apps, such as MyFitnessPal or Strava, to track your workouts and sync the data with HealthKit.

For example, let’s read the step count data;

let stepsCount = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let startDate = Calendar.current.date(byAdding: .day, value: -7, to: Date())
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: Date(), options: .strictStartDate)

let query = HKSampleQuery(sampleType: stepsCount, predicate: predicate, limit: Int(HKObjectQueryNoLimit), sortDescriptors: nil) { (query, results, error) in
guard let samples = results as? [HKQuantitySample] else {
return
}

let totalSteps = samples.reduce(0, {$0 + $1.quantity.doubleValue(for: HKUnit.count())})
print("Last 7 days step count: \(totalSteps)")
}
healthStore.execute(query)
  • Monitoring Vital Signs

HealthKit can also be used to monitor vital signs, such as your heart rate and blood pressure. With the help of third-party devices, such as blood pressure monitors or heart rate monitors, you can easily track this data and share it with your doctor or other healthcare professionals.

For example, let’s write a screen that prints your beautiful heartbeats on the screen;

import UIKit
import HealthKit

class ViewController: UIViewController {

let healthStore = HKHealthStore()
var heartRateQuery: HKObserverQuery?

@IBOutlet weak var heartRateLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()

// Check if HealthKit is available on this device
guard HKHealthStore.isHealthDataAvailable() else {
print("HealthKit is not available on this device")
return
}

// Set the types of data we want to read from HealthKit
let readDataTypes: Set<HKObjectType> = [
HKObjectType.quantityType(forIdentifier: .heartRate)!
]

// Request authorization to read the data types
healthStore.requestAuthorization(toShare: nil, read: readDataTypes) { (success, error) in
if let error = error {
print("Error requesting authorization: \(error.localizedDescription)")
return
}

// Start the heart rate observer query
self.startHeartRateObserverQuery()
}
}

func startHeartRateObserverQuery() {
// Set up the heart rate observer query
let heartRateType = HKObjectType.quantityType(forIdentifier: .heartRate)!
heartRateQuery = HKObserverQuery(sampleType: heartRateType, predicate: nil) { (query, completionHandler, error) in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}

// Get the most recent heart rate sample
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
let heartRateSampleQuery = HKSampleQuery(sampleType: heartRateType, predicate: nil, limit: 1, sortDescriptors: [sortDescriptor]) { (query, samples, error) in
if let error = error {
print("Error: \(error.localizedDescription)")
return
}

// Update the UI with the heart rate value
if let heartRateSample = samples?.first as? HKQuantitySample {
let heartRateUnit = HKUnit.count().unitDivided(by: HKUnit.minute())
let heartRate = Int(heartRateSample.quantity.doubleValue(for: heartRateUnit))
DispatchQueue.main.async {
self.heartRateLabel.text = "\(heartRate) bpm"
}
}
}

// Execute the heart rate sample query
self.healthStore.execute(heartRateSampleQuery)

// Call the completion handler
completionHandler()
}

// Add the heart rate observer query to the health store
healthStore.execute(heartRateQuery!)
}

deinit {
// Stop the heart rate observer query
healthStore.stop(heartRateQuery!)
}

}
  • Monitoring Sleep

Getting enough sleep is essential for good health, and HealthKit can help you track your sleep patterns. You can monitor how long you sleep each night, the quality of your sleep, and even your bedtime routine. This data can help you identify areas where you need to improve your sleep habits.

You can choose to track your sleep and keep the nights a little shorter :)

import HealthKit

let healthStore = HKHealthStore()

// Request authorization to access sleep data
let sleepType = HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier.sleepAnalysis)!
healthStore.requestAuthorization(toShare: nil, read: [sleepType]) { (success, error) in
if success {
// Query for sleep data
let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false)
let query = HKSampleQuery(sampleType: sleepType, predicate: nil, limit: 30, sortDescriptors: [sortDescriptor]) { (query, samples, error) in
guard let samples = samples as? [HKCategorySample], error == nil else {
print("Failed to fetch sleep data: \(error!.localizedDescription)")
return
}
for sample in samples {
let startDate = sample.startDate
let endDate = sample.endDate
print("Sleep start: \(startDate), end: \(endDate)")
}
}
healthStore.execute(query)
} else {
print("Authorization to access sleep data was denied.")
}
}

In conclusion, HealthKit is a powerful tool that can help you take control of your health and wellbeing. Whether you want to monitor your daily activity, track your vital signs, manage your medications, or monitor your sleep, HealthKit has you covered. With its user-friendly interface and seamless integration with third-party devices, HealthKit makes it easy to stay on top of your health goals. So why not give it a try and see how it can improve your life? Remember, your health is your wealth, and HealthKit is here to help you achieve it.

Have a healthy weekend everyone ❤

--

--