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.
I created a new Xcode project named "HealthKitSample" for the following screenshots. Configuring the project to access HealthKit involves [^1]:
add HealthKit capability
![Xcode window–add capability](./assets/Xcode-HealthKitSample — HealthKitSample.xcodeproj-20230405-142509.png)
in the now open modal dialog,![Xcode modal-add capability](./assets/Finder-2212 Swisscom cxml-20230405-143239.png)
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)
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"
To wrap all functionality concerning accessing health data, I create a new file called
HealthKitController. Here, the first action is to
[^1]: this tutorial was written/screenshots were taken on Xcode 14.3