Accessing HealthKit data

Link Collection

  • https://www.applicoinc.com/blog/healthkit/ (written at iOS8 timeframe, generic information)
  • https://www.appcoda.com/healthkit/ (from 2017, but still relevant with code examples)
  • https://brunoscheufler.com/blog/2021-11-07-accessing-workouts-with-healthkit-and-swift (most recent, from 2017, pretty concise)

Privacy

Apple emphasises privacy everywhere–which includes health data. While writing to HealthKit is not a privacy issue, reading from it means that your app needs the users' permission to do so. More specifically, the permissions are set on the different types of health information–so an app might have access to a specific information, but not to another.

Not having access to a specific information will lead to a non-existing value. The framework won't tell you that you don't have access if you don't, rather the data will be nil.

Configure Xcode to get access to HealthKit

I created a new Xcode project named "HealthKitSample" for the following screenshots. Configuring the project to access HealthKit involves [^1]:

  1. add HealthKit capability

    ![Xcode window–add capability](./assets/Xcode-HealthKitSample — HealthKitSample.xcodeproj-20230405-142509.png)

    1. select the app in the Project Navigator
    2. select the target you want to apply the capability to
    3. select "Signing & Capabilities" in the main window
    4. click the "+ Capabilities" button
  2. in the now open modal dialog,![Xcode modal-add capability](./assets/Finder-2212 Swisscom cxml-20230405-143239.png)

    1. fill in "Health in the search field"
    2. double-click on the "HealthKit" entry in the left panel
  3. this results the following screen, which includes the just added capability: ![Xcode-HealthKitSample — HealthKitSample.xcodeproj-20230405-144700](./assets/Xcode-HealthKitSample — HealthKitSample.xcodeproj-20230405-144700.png)

Please be aware of the fact that you need to have a "Team" assigned in the signing section–if you don't, you are met with this error message: ![Typora-Accessing HealthKit data.md-20230405-144406](./assets/Typora-Accessing HealthKit data.md-20230405-144406.png)

Add HealthKit usage description

To be able to prompt the user to give access to the data, a NSHealthShareUsageDescription must be added to the Info.plist. If this entry is missing, Xcode will provide us with an error if we start the app in the simulator: Thread 1: "NSHealthShareUsageDescription must be set in the app's Info.plist in order to request read authorization for the following types: HKCharacteristicTypeIdentifierBiologicalSex"

Accessing data

To wrap all functionality concerning accessing health data, I create a new file called HealthKitController. Here, the first action is to import HealthKit.

Next steps

  • access cycling events

[^1]: this tutorial was written/screenshots were taken on Xcode 14.3