Apple HealthKit and accessing its Clinical records and Health data
Health and fitness have become very important now than it ever was. Well, it’s not something about age anymore, everybody wants to be fit, be it the old or the young. This is what brings the advancements in tech, the mobile apps, and hardware in particular which are bringing this into a whole new light.
Apple’s Health Kit has played a huge huge role in all this, and I must say its one beautiful feature not just for the users out there but the developers too.
I would recommend you all look at Apple’s Health Kit documentation (which is, of course, the best) for the detailed insights about Health Kit. What I’ll be doing next in this article is to give y’all a brief about its working from a simple application.
Let's start with the initial thing, you definitely need to have a developer account. Once you have that assign your team and we are good to go!
Entitlements
Enable the required entitlements. Open the Capabilities tab in the target editor, and turn on the HealthKit switch.
Permissions
HealthKit deals with sensitive and private data.
You need to describe why you are asking for health metrics from your users.
Open Info.plist. Then add the following keys:
Privacy — Health Share Usage Description
Privacy — Health Update Usage Description
Authorize HealthKit
The method below accepts no parameters, and it has a completion handler that returns a boolean (success or failure) and an optional error in case something goes wrong.
To authorize HealthKit, the authorizeHealthKit(completion:) method will need to do these four things:
- Check to see if Healthkit is available on this device. If it isn’t, complete with failure and an error.
- Prepare the types of health data our app will read or write from HealthKit.
- Organize those data into a list of types to be read and types to be written.
- Request Authorization — if it’s successful, complete with success.
The HKHealthStore represents the central repository that stores the health data and we are going to interact a lot with it. HKHealthStore’s isHealthDataAvailable() method helps you figure out if the user’s current device supports HeathKit data.
Preparing Data Types
HealthKit has many data types, refer them here: https://developer.apple.com/documentation/health kit/data_types.
Check the type of data you need and start building guard statements as mentioned below, to read and write data.
Read and write the Data
Make a list of data you want to read and write. Remember, clinical records are read-only, hence only health data will be written as well as read.
Authorize Data
Final Step!
You just need to request authorization from HealthKit. Request authorization from HealthKit and then call your completion handler.
And you are good to go! You can now access data from the HealthKit, also remember the HealthKit Permission screen UI cannot be modified except for the data you need to read and write.