HealthKit Tutorial With Swift: Getting Started

Learn how to request permission to access HealthKit data, as well as read and write data to HealthKit’s central repository in this HealthKit tutorial. By Ted Bendixson.

4.5 (15) · 1 Review

Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

Saving Samples

Prancercise Tracker already has a convenient body mass index calculator. Let’s use it to record a sample of your user’s BMI.

Open ProfileDataStore.swift and add the following method:

class func saveBodyMassIndexSample(bodyMassIndex: Double, date: Date) {
  
  //1.  Make sure the body mass type exists  
  guard let bodyMassIndexType = HKQuantityType.quantityType(forIdentifier: .bodyMassIndex) else {
    fatalError("Body Mass Index Type is no longer available in HealthKit")
  }
    
  //2.  Use the Count HKUnit to create a body mass quantity
  let bodyMassQuantity = HKQuantity(unit: HKUnit.count(),
                                    doubleValue: bodyMassIndex)
    
  let bodyMassIndexSample = HKQuantitySample(type: bodyMassIndexType,
                                             quantity: bodyMassQuantity,
                                             start: date,
                                             end: date)
    
  //3.  Save the same to HealthKit
  HKHealthStore().save(bodyMassIndexSample) { (success, error) in
      
    if let error = error {
      print("Error Saving BMI Sample: \(error.localizedDescription)")
    } else {
      print("Successfully saved BMI Sample")
    }
  }
}

Some of this will seem familiar. As with other sample types, you first need to make sure the sample type is available in HealthKit.

  1. In this case, the code checks to see if there is a quantity type for body mass index. If there is, it gets used to create a quantity and quantity sample. If not, the app intentionally crashes.
  2. The count() method on HKUnit is for a special case when there isn’t a clear unit for the type of sample you are storing. At some point in the future, there may be a unit assigned to body mass index, but for now this more generic unit works just fine.
  3. HKHealthStore saves the sample and lets you know if the process was successful from a trailing closure. You could do more with this, but for the now the app just prints to the console.

Almost done. Let’s hook this thing up the user interface.

Open ProfileViewController.swift, find the saveBodyMassIndexToHealthKit() method. This method gets called when the user taps the Save BMI button in the table view.

Paste the following lines of code into the method:

guard let bodyMassIndex = userHealthProfile.bodyMassIndex else {
  displayAlert(for: ProfileDataError.missingBodyMassIndex)
  return
}
    
ProfileDataStore.saveBodyMassIndexSample(bodyMassIndex: bodyMassIndex,
                                         date: Date())

You will recall that the body mass index is a computed property which returns a value when both height and weight samples have been loaded from HealthKit. This code attempts to compute that property, and if it can, it gets passed to the savedBodyMassIndexSample(bodyMassIndex: date:) method you just wrote.

It also shows a handy alert message if body mass index can’t be computed for some reason.

Build and run Prancercise Tracker one final time. Go into the Profile & BMI screen. Load your data from HeathKit, then tap the Save BMI button.

Take a look at the console. Do you see this?

Successfully saved BMI Sample

If you do, congratulations! Your BMI sample is now stored in HealthKit’s central repository. Let’s see if we can find it.

Open the Health app, tap the Health Data tab, Tap on Body Measurements in the table view, and then tap on Body Mass Index.

Unless you regularly record your body mass index (as all high profile prancercisers do), you should see a single data point like this one:

Sweet. You can see the sample from an app of your own creation, right there in Apple’s Health app. Imagine the possibilities.

Where To Go From Here?

Here is the example app with all of the modifications we have made up to this point.

Congratulations, you’ve got some hands-on experience with HealthKit! You now know how to request permissions, read biological characteristics, and read and write samples.

If you want to learn more, stay tuned for the next part of this HealthKit tutorial series where you’ll learn more about a more complex type of data: workouts.

In the meantime, if you have any questions or comments, please join the forum discussion below!