@krantzr/react-native-health
v2.1.0
Published
(FORK) A React Native package to interact with Apple HealthKit
Maintainers
Readme
React Native Health
A React Native package to interact with Apple HealthKit for iOS. Maintained with ❤️ by AE Studio.
This package allows access to health & fitness data exposed by Apple Healthkit. You can see the methods available here.
If you are looking for a more robust solution providing normalized data, insights and recommendations based on user's biometric data, data from multiple sources (Fitbit, Oura), or a hosted solution, please check out the Point SDK developed by our frens.
METER HEALTH
Fork changelog:
Upgrading from 1.x? See the migration guide for what changes from the app's perspective.
2.0.0
- New Architecture / TurboModule support. The module ships a codegen spec
(
src/NativeAppleHealthKit.ts) and is registered as a TurboModule, so it works in bridgeless mode (React Native 0.76+ / Expo SDK 52+) without the interop layer. The JS API is unchanged. - Background observers no longer need the bridge:
initializeBackgroundObservers()replacesinitializeBackgroundObservers:bridge(the old selector still exists but ignores its argument). Events are delivered through the regularNativeEventEmitterin both architectures. - Expo config plugin: new
enableBackgroundObserversoption that wires the AppDelegate call and the background-delivery entitlement for you. - HealthKit API updates:
saveWorkoutusesHKWorkoutBuilder(theHKWorkoutinitializer is deprecated since iOS 17), workout energy/distance are read from workout statistics (totalEnergyBurned/totalDistanceare deprecated since iOS 18), and theSwimBikeRun,Transition,UnderwaterDivingandOtheractivity types were added. - HealthKit data types brought up to the iOS 26 SDK: 43 additional quantity types
(cycling power/cadence/speed/FTP, physical effort, time in daylight, workout effort
score, mobility metrics, HRR, AFib burden, sleeping wrist temperature, breathing
disturbances, cross-country skiing / rowing / paddle / skating distance & speed, ...)
and 68 category types (symptoms, heart / hearing / mobility events, sleep apnea,
hypertension, reproductive health, ...) are now requestable as permissions and
readable through
getSamples. Read-only Apple types are filtered out of write permissions instead of failing the whole authorization request. getSamplesaccepts any readable permission name, picks a fitting unit when none (or an incompatible one) is given, and returns category samples with theirvalue.- More units (
watt,rpm,meterPerSecond,kmPerHour,kcalPerKgHour,appleEffortScore, ...), plus any raw HealthKit unit string. - New APIs: State of Mind (
getStateOfMindSamples/saveStateOfMind), GAD-7 & PHQ-9 scored assessments (getScoredAssessments/saveScoredAssessment) on iOS 18+, and the read-only Medications API (getUserAnnotatedMedications/getMedicationDoseEvents) on iOS 26+. Permissions:StateOfMind,GAD7Assessment,PHQ9Assessment,MedicationDoseEvent,UserAnnotatedMedications. On older iOS the methods return an error instead of crashing; building them needs Xcode 16 / Xcode 26 respectively (older SDKs compile them out). - Requires React Native >= 0.71 and iOS 15.1+.
- Breaking:
saveWorkoutnow needs write permission forActiveEnergyBurned(whenenergyBurnedis given) and the matching distance type (whendistanceis given), in addition toWorkout.
1.x
- Added save functions for:
- Heartrate variability
- Resting heartrate
- Active Energy
- Basal Energy
- Vo2Max
- OxygenSaturation
- Respiratory rate
- SleepAnalysis
New Version
(August 2023)
We're thrilled to share that we're in the midst of creating a significant update for this library. The upcoming version will be crafted using Swift (bye-bye, Objective-C! 👋) and will showcase a fresh new interface.
We're currently preparing to make it available for opt-in users in the near future, and we're extending a warm invitation for you all to join us in shaping this endeavor.
As we are fully focused in it, we're temporarily holding off on introducing new features. However, we're eagerly welcoming pull requests that address critical bug fixes or tackle dependency issues. Your contributions will not only be highly appreciated but also swiftly integrated and deployed. 💖
Discord
Getting Started
🚨 Expo: This package is not available in the Expo Go app. Learn how you can use it with custom dev clients.
Automatic Installation
- Install the react-native-health package from npm
yarn add react-native-health- If you are using CocoaPods you can run the following
from the
ios/folder of your app
pod installOr, if you need to manually link it, run
react-native link react-native-health- Update the
ios/<Project Name>/info.plistfile in your project
<key>NSHealthShareUsageDescription</key>
<string>Read and understand health data.</string>
<key>NSHealthUpdateUsageDescription</key>
<string>Share workout data with other apps.</string>
<!-- Below is only required if requesting clinical health data -->
<key>NSHealthClinicalHealthRecordsShareUsageDescription</key>
<string>Read and understand clinical health data.</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'
To enable access to clinical data types, check the Clinical Health Records box.
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.
Register the observers once at app launch. With the Swift AppDelegate.swift that
React Native 0.77+ templates ship with:
import RNAppleHealthKit
@main
class AppDelegate: RCTAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
/* Add Background initializer for HealthKit */
RCTAppleHealthKit().initializeBackgroundObservers()
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}Or, with an Objective-C AppDelegate.mm:
#import <RNAppleHealthKit/RCTAppleHealthKit.h>
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
/* Add Background initializer for HealthKit */
[[RCTAppleHealthKit new] initializeBackgroundObservers];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}Expo projects don't edit the AppDelegate by hand: set enableBackgroundObservers: true
on the config plugin instead (see Expo).
The HealthKit "Background Delivery" capability
(com.apple.developer.healthkit.background-delivery entitlement) must be enabled for
iOS to wake the app when new samples arrive.
After that you can start listening for data updates using the React Native client. For more information, see background observers.
Documentation
All the documentation is under the docs folder. They are split into the following categories:
Constants
Base Methods
Mental Wellbeing Methods (iOS 18+)
Medication Methods (iOS 26+)
Background Methods
- background observers
- initStepCountObserver - DEPRECATED
- setObserver - DEPRECATED
Activity Methods
Body Methods
- getLatestHeight
- getLatestWeight
- getHeightSamples
- getWeightSamples
- getBodyTemperatureSamples
- getLatestBodyFatPercentage
- getBodyFatPercentageSamples
- getLatestLeanBodyMass
- getLeanBodyMassSamples
- saveHeight
- saveWeight
- saveBodyFatPercentage
- saveBodyTemperature
- saveLeanBodyMass
Characteristic Methods
Clinical Records Methods
Dietary Methods
- getEnergyConsumedSamples
- getProteinSamples
- getFiberSamples
- getTotalFatSamples
- saveFood
- saveWater
- getWater
- getWaterSamples
- getFiberSamples
- getInsulinDeliverySamples
- saveInsulinDeliverySamples
- deleteInsulinDeliverySamples
Fitness Methods
- getDailyStepCountSamples
- getStepCount
- getSamples
- getDailyDistanceWalkingRunningSamples
- getDistanceWalkingRunning
- getDailyDistanceSwimmingSamples
- getDistanceSwimming
- getDailyDistanceCyclingSamples
- getDistanceCycling
- getDailyFlightsClimbedSamples
- getFlightsClimbed
- saveSteps
- saveWalkingRunningDistance
Hearing Methods
Lab Tests Methods
- getBloodAlcoholContentSamples
- getBloodGlucoseSamples
- getLatestBloodAlcoholContent
- saveBloodAlcoholContent
- saveBloodGlucoseSample
- deleteBloodGlucoseSample
Nutrition
Mindfulness Methods
Sleep Methods
Vitals Methods
- getBloodPressureSamples
- getElectrocardiogramSamples
- saveHeartRateSample
- getHeartRateSamples
- getHeartRateVariabilitySamples
- getHeartbeatSeriesSamples
- getOxygenSaturationSamples
- getRestingHeartRateSamples
- getVo2MaxSamples
- getLatestBmi
- getBmiSamples
- getRespiratoryRateSamples
- getWalkingHeartRateAverage
- saveBmi
Workout Methods
Additional Information
Permissions
Due to Apple's privacy model, if a user has previously denied a specific permission they will not be prompted again for that permission. The user will need to go into the Apple Health app and grant the permission to your app.
For any data written to Healthkit, an authorization error can be caught. If an authorization error occurs, you can prompt the user to set the specific permission or add the permission to the options object when initializing the library.
If extra read or write permissions are added to the options object, the app will request the user's permission when the library is initialized again.
Manual Installation
- Run
yarn add react-native-health - In XCode, in the project navigator, right-click
Libraries➜Add Files to [your project's name] - Go to
node_modules➜react-native-healthand addRCTAppleHealthkit.xcodeproj - In XCode, in the project navigator, select your project. Add
libRCTAppleHealthkit.ato your project'sBuild Phases➜Link Binary With Libraries - Click
RCTAppleHealthkit.xcodeprojin the project navigator and go theBuild Settingstab. Make sure 'All' is toggled on (instead of 'Basic'). In theSearch Pathssection, look forHeader Search Pathsand make sure it contains both$(SRCROOT)/../../react-native/Reactand$(SRCROOT)/../../../React- mark both asrecursive. - Enable Healthkit in your application's
Capabilities
- Compile and run
Contributing
We appreciate any requests and contributions to react-native-health.
The issues tracker
is used to keep a list of features and bugs to be worked on. Please see our
contributing documentation
for some tips on getting started.
References
Android Alternative
If your app needs an Android + Health Connect integration, your princess is in another castle. You can use the package React Native Health Connect maintained by one of the community's dev.
In case of questions or if you just want to congratz the author, you can reach out to him on our Discord Server.
Acknowledgement
This package is a fork of rn-apple-healthkit
This package also inherits additional features from Nutrisense fork
Plz I Still Need Halp
This package is maintained with ❤️ by AE Studio. We will do our best to respond to requests and support for this package so please get in touch! If you require more extensive help or have other design, data science or development needs - we are a full service product development agency and can build pretty much anything so hit us up!
