Article

Setting Up HealthKit

Set up and configure your HealthKit store.

Overview

Before using HealthKit, you must perform the following steps:

  1. Enable HealthKit in your app.

  2. Ensure that HealthKit is available on the current device.

  3. Create your app’s HealthKit store.

  4. Request permission to read and share data.

For a practical example of how to set up and use HealthKit, see SpeedySloth: Creating a Workout.

Enable HealthKit

Before you can use HealthKit, you must add the HealthKit capabilities for your app. In Xcode, select the project and turn on the HealthKit capability (see Figure 1). Only enable the Health Records checkbox if your app needs to access the user’s clinical records. App Review may reject apps that enable the Health Records capability if the app doesn’t use the Health Record data. For more information, see Accessing Health Records.

Figure 1

Enable HealthKit capabilities

A screenshot showing the HealthKit capabilities.

For a detailed discussion about enabling capabilities, see Configure HealthKit in Xcode Help.

When you enable the HealthKit capabilities on an iOS app, Xcode adds HealthKit to the list of required device capabilities. This prevents users from purchasing or installing the app on devices that don’t support HealthKit.

If HealthKit isn’t required for the correct operation of your app, you can open the app’s Info.plist file and delete the healthkit entry from the Required device capabilities array. The healthkit entry isn’t used by WatchKit extensions.

For more information on required device capabilities, see the UIRequiredDeviceCapabilities key in Information Property List Key Reference.

Ensure HealthKit’s Availability

Call the isHealthDataAvailable() method to confirm that HealthKit is available on the user's device.

if HKHealthStore.isHealthDataAvailable() {
    // Add code to use HealthKit here.
}

Call this method before calling any other HealthKit methods. If HealthKit is not available on the device (for example, on an iPad), other HealthKit methods fail with an errorHealthDataUnavailable error. If HealthKit is restricted (for example, in an enterprise environment), the methods fail with an errorHealthDataRestricted error.

Create the HealthKit Store

If HealthKit is both enabled and available, instantiate an HKHealthStore object for your app as shown:

let healthStore = HKHealthStore()

You need only a single HealthKit store per app. These are long-lived objects; you create the store once, and keep a reference for later use.

Request Permission to Read and Share Data

To help protect the user’s privacy, HealthKit requires fine-grained authorization. You must request permission to both read and share each data type used by your app before you attempt to access or save the data. However, you don’t need to request permission for all data types at once. Instead, it may make more sense to wait until you need to access the data before asking for permission.

The example below shows the SpeedySloth app asking for permission to read and share energy burned, cycling distance, walking or running distance, and heart rate samples.

let allTypes = Set([HKObjectType.workoutType(),
                    HKObjectType.quantityType(forIdentifier: .activeEnergyBurned)!,
                    HKObjectType.quantityType(forIdentifier: .distanceCycling)!,
                    HKObjectType.quantityType(forIdentifier: .distanceWalkingRunning)!,
                    HKObjectType.quantityType(forIdentifier: .heartRate)!])

healthStore.requestAuthorization(toShare: allTypes, read: allTypes) { (success, error) in
    if !success {
        // Handle the error here.
    }
}

Any time your app requests new permissions, the system displays a form with all the requested data types shown. The user can toggle individual read and share permissions on and off, as in Figure 2. To learn how to provide a great user experience when asking for permissions, see HealthKit in iOS Human Interface Guidelines.

Figure 2

Request permission for the Fit app

A screenshot of the permission form for the Fit app.

You must also provide custom messages for the permissions sheet. Xcode requires a separate custom message for reading and writing HealthKit data. In your app’s Info.plist, set the NSHealthShareUsageDescription key to customize the message for reading data. Set the NSHealthUpdateUsageDescription key to customize the message for writing data.

For more information, see iOS Keys in Information Property List Key Reference.

If the user grants permission to share a data type, you can create new samples of that type and save them to the HealthKit store. However, before attempting to save any data, check to see if your app is authorized to share that data type by calling the authorizationStatus(for:) method. If you have not yet requested permission, any attempts to save fail with an HKError.Code.errorAuthorizationNotDetermined error. If the user has denied permission, attempts to save fail with an HKError.Code.errorAuthorizationDenied error.

To help protect the user’s privacy, your app does not know whether the user granted or denied permission to read data from HealthKit. If the user denied permission, attempts to query data from HealthKit return only samples that your app successfully saved to the HealthKit store.

Requesting permission to read and share data is only one part of protecting your user’s privacy. For more information, see Protecting User Privacy.

Specify Required Clinical Record Types

If your app requires access to specific clinical record data to function properly, specify the required clinical record types in your app’s Info.plist file using the NSHealthRequiredReadAuthorizationTypeIdentifiers key. This key defines the data types that your app must have permission to read. Set the value to an array of strings containing the type identifiers for your required types. For a list of type identifiers, see HKClinicalTypeIdentifier.

To protect the user’s privacy, you must specify three or more required clinical record types. If the user denies authorization to any of the types, authorization fails with an HKError.Code.errorRequiredAuthorizationDenied error; your app is not told which record types the user denied access to.

Topics

Entitlements

HealthKit Entitlement

A Boolean value that indicates whether the app may request user authorization to access health and activity data that appears in the Health app.

Key: com.apple.developer.healthkit
HealthKit Capabilities Entitlement

Health data types that require additional permission.

Key: com.apple.developer.healthkit.access

Information Property List Keys

property list key NSHealthUpdateUsageDescription

A message to the user that explains why the app requested permission to save samples to the HealthKit store.

Name: Privacy - Health Update Usage Description
property list key NSHealthShareUsageDescription

A message to the user that explains why the app requested permission to read samples from the HealthKit store.

Name: Privacy - Health Share Usage Description
property list key NSHealthRequiredReadAuthorizationTypeIdentifiers

The clinical record data types that your app must get permission to read.

property list key NSHealthClinicalHealthRecordsShareUsageDescription

A message to the user that explains why the app requested permission to read clinical records.

Name: Privacy - Health Records Usage Description

See Also

Health

property list key NSHealthClinicalHealthRecordsShareUsageDescription

A message to the user that explains why the app requested permission to read clinical records.

Name: Privacy - Health Records Usage Description
property list key NSHealthShareUsageDescription

A message to the user that explains why the app requested permission to read samples from the HealthKit store.

Name: Privacy - Health Share Usage Description
property list key NSHealthUpdateUsageDescription

A message to the user that explains why the app requested permission to save samples to the HealthKit store.

Name: Privacy - Health Update Usage Description
property list key NSHealthRequiredReadAuthorizationTypeIdentifiers

The clinical record data types that your app must get permission to read.