React Native Health

A React Native package to interact with Apple HealthKit for iOS.

Getting Started

Automatic Installation

  1. Install the react-native-health package from npm
yarn add react-native-health
  1. If you are using CocoaPods you can run the following
    from the ios/ folder of your app
pod install

Or, if you need to manually link it, run

react-native link react-native-health
  1. Update the ios/<Project Name>/info.plist file in your project
<key>NSHealthShareUsageDescription</key>
<string>Read and understand health data.</string>
<key>NSHealthUpdateUsageDescription</key>
<string>Share workout data with other apps.</string>

To add Healthkit support to your application's Capabilities

  • Open the ios/ folder of your project in Xcode
  • Select the project name in the left sidebar
  • In the main view select '+ Capability' and double click 'HealthKit'

Usage

In order to start collecting or saving data to HealthKit, you need to request
the user's permissions for the given data types. It can be done in the following
way

import AppleHealthKit, {
  HealthValue,
  HealthKitPermissions,
} from 'react-native-health'

/* Permission options */
const permissions = {
  permissions: {
    read: [AppleHealthKit.Constants.Permissions.HeartRate],
    write: [AppleHealthKit.Constants.Permissions.Steps],
  },
} as HealthKitPermissions

AppleHealthKit.initHealthKit(permissions, (error: string) => {
  /* Called after we receive a response from the system */

  if (error) {
    console.log('[ERROR] Cannot grant permissions!')
  }

  /* Can now read or write to HealthKit */

  const options = {
    startDate: new Date(2020, 1, 1).toISOString(),
  }

  AppleHealthKit.getHeartRateSamples(
    options,
    (callbackError: string, results: HealthValue[]) => {
      /* Samples are now collected from HealthKit */
    },
  )
})

Background Processing

For background capabilities, Apple allows developers to setup long running observer
queries for the health types needed.

To setup that in your app, in XCode open your ios/AppDelegate.m file and add the
following statements:

#import "AppDelegate.h"

...

/* Add the library import at the top of AppDelegate.m */
#import "RCTAppleHealthKit.h"

...

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self
                                            launchOptions:launchOptions];

  ...

  /* Add Background initializer for HealthKit  */
  [[RCTAppleHealthKit new] initializeBackgroundObservers:bridge];

  ...

  return YES;
}

After that you can start listening for data updates using the React Native
client.

GitHub

https://github.com/agencyenterprise/react-native-health