Requesting access to the HealthKit Store

Applications that want access to health-related data must ask permission for every type of data they want to access. If your app requires access to heart rate data, weight data, and activity data, that means that you must request access for each different data type. A single authorization request can ask for access to multiple data types at once, and the user can manually decide which data types can be accessed.

When you want to use certain data types from the HealthKit store, it's essential that you make sure your user understands why you need access to this data and to request access at an appropriate time. If your app has an onboarding flow, you could add a page that outlines the health data your app needs and asks the user for permission once they understand why you need access. The following screenshot shows the access dialog where users can configure the type of data an app is allowed to access:

The preceding screenshot shows all the different categories that this app wants to have read and write access for. An authorization request is performed to request access to a set of HealthKit categories. The following code is an example of the request that was used for the screenshot:

let objectTypes: Set<HKSampleType> = [HKObjectType.workoutType(), HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!, HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!]

healthKitStore.requestAuthorization(toShare: objectTypes, read: objectTypes) { success, error in
  print(success)
  print(error)
}

A user can revoke access to data at any time in the Health app, so apps must make sure that they presently have access to data before attempting to use it. The following code shows a sample of how to retrieve the authorization status for the .distanceWalkingRunning quantity type:

let objectType = HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!
let status = healthKitStore.authorizationStatus(for: objectType)

The possible values for the authorization status are the following:

Your app can't determine whether reading from the store is allowed. The reasoning for this is that denying an app access to data might hint that the user has something to hide. Since health data is very personal, it's important that apps can't make any assumptions based on the access they do or do not have the HealthKit. This means that if an app queries data while it doesn't have read access, HealthKit will return an empty result set. If the app has write access to HealthKit, only the results that the app wrote to the store will be returned.