react-native-health

repository·master·Indexed 22 days ago

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

A React Native package (v1.19.0) that provides an interface to Apple HealthKit on iOS. It allows developers to read, write, and observe health and fitness data, including body metrics, vitals, activity tracking, dietary data, sleep, and clinical records. The library supports background observers for specific data types like step counts and heart rate, and requires custom native configuration in Xcode and AppDelegate.m.

Tokens
57.8K
Snippets
162
Records
183
Agent score
77%

What's inside react-native-health

  1. Overview of react-native-health API categories

    master

    The react-native-health library provides a comprehensive interface for interacting with Apple HealthKit. The API is organized into several functional categories:

    • Base Methods: Core lifecycle and initialization methods like isAvailable, initHealthKit, and getAuthStatus.
    • Background Methods: Methods for setting up observers to track data changes in the background, such as initStepCountObserver.
    • Body & Vitals: Access and save physical metrics including weight, height, BMI, heart rate, blood pressure, and oxygen saturation.
    • Fitness & Activity: Track steps, distance (walking, running, swimming, cycling), flights climbed, and energy burned.
    • Dietary & Lab Tests: Manage nutritional data (water, fat) and clinical data (blood glucose, blood alcohol content).
    • Mindfulness & Sleep: Access mindfulness session data and sleep samples.
    • Characteristic Methods: Retrieve biological data like sex, blood type, and date of birth.
    • Hearing & Clinical: Access environmental audio exposure and clinical records.

    Use the specific method categories to find the appropriate functions for your health-tracking requirements.

  2. Track step counts in the background using Background Methods

    master

    To react to changes in step counts even when the app is not in the foreground, use the background observer methods:

    • initStepCountObserver(options): Sets up an observer specifically for step count changes.
    • setObserver(options): Configures a general observer for health data changes.
  3. Manage background data with Background Methods

    master
    The library supports background processing through background observers. Note that initStepCountObserver and setObserver are marked as DEPRECATED. You should use the modern background observers implementation to monitor health changes while the app is not in the foreground.
  4. Handle HealthKit Permissions and Errors

    master

    Permission Denial

    Due to Apple's privacy model, if a user denies a permission, they will not be prompted again. To fix this, the user must manually grant permission within the Apple Health app.

    Authorization Errors

    If you attempt to write data and encounter an authorization error, you can catch it in your callback. To resolve this, you can:

    1. Prompt the user to set the specific permission in the Health app.
    2. Add the missing permission to the permissions object in your next initHealthKit call. Adding extra read or write permissions to the options object will trigger a new permission request from the system.
  5. How setObserver works for HealthKit updates

    master

    An observer listens to HealthKit updates and notifies your app when new data is added. This is useful for detecting changes in HealthKit data while the app is running.

    Supported Data Identifiers:

    • Cycling
    • HeartRate
    • RestingHeartRate
    • Running
    • StairClimbing
    • Walking
    • Workout

    Note on Frequency: Some data types (like step counts) have a minimum frequency of HKUpdateFrequencyHourly, which is enforced by the system.

  6. Enable HealthKit Capability in Xcode

    master

    To allow your app to use HealthKit, you must enable the capability in Xcode:

    1. Open the ios/ folder of your project in Xcode.
    2. Select your project in the left sidebar.
    3. Select the '+ Capability' button in the main view.
    4. Double-click 'HealthKit'.
    5. (Optional) If you need to access clinical data, check the Clinical Health Records box.
  7. Enable HealthKit Capabilities for Production

    master

    The react-native-health plugin automatically enables the iOS com.apple.developer.healthkit entitlement. However, to ensure this matches your production bundle identifier's capabilities, you must follow one of these paths:

    • Automatic: Use EAS Build to build your app.
    • Manual:
      • Visit the Apple Developer Portal and enable the HealthKit capability for your specific bundle identifier before building for production.
      • Alternatively, enable the capability directly via Xcode.
  8. Install react-native-health

    master

    To install the package, use yarn to add the dependency and then install the iOS pods.

    Note for Expo users: This package is not available in the Expo Go app. You must use custom dev clients to use this library.

    Automatic Installation

    1. Install the package:
    yarn add react-native-health
    1. Install CocoaPods:
    cd ios && pod install

    Alternatively, if you need to manually link, run:

    react-native link react-native-health
    yarn add react-native-health
    cd ios && pod install
  9. Install react-native-health via Manual Installation

    master

    If automatic installation and auto-linking fail, follow these steps in Xcode to manually integrate the library:

    1. Add the project: In Xcode, right-click LibrariesAdd Files to [your project's name]. Navigate to node_modules/react-native-health and select RCTAppleHealthkit.xcodeproj.
    2. Link the library: Select your project in the navigator. Under Build PhasesLink Binary With Libraries, add libRCTAppleHealthkit.a.
    3. Configure Header Search Paths: Select RCTAppleHealthkit.xcodeproj in the navigator. In the Build Settings tab (ensure 'All' is selected), find Header Search Paths and add the following as recursive:
      • $(SRCROOT)/../../react-native/React
      • $(SRCROOT)/../../../React
    4. Enable HealthKit: In your application's Capabilities section in Xcode, enable the HealthKit capability.
    5. Compile and run your project.
  10. Configure Background Observers in iOS

    master

    To enable your app to listen for Apple HealthKit updates in the background, you must initialize the background observers in your iOS native code.

    Open your ios/AppDelegate.m file and perform the following steps:

    1. Import RCTAppleHealthKit.h at the top of the file.
    2. Inside the application:didFinishLaunchingWithOptions: method, call [[RCTAppleHealthKit new] initializeBackgroundObservers:bridge]; after the bridge has been initialized.

    Note: If you have already completed the 'Background Processing' steps mentioned in the main README, you can skip this manual initialization.

    #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 alloc] initWithDelegate:self
                                                launchOptions:launchOptions];
    
      ...
    
      /* Add Background initializer for HealthKit  */
      [[RCTAppleHealthKit new] initializeBackgroundObservers:bridge];
    
      ...
    
      return YES;
    }
  11. Install react-native-health in Expo

    master

    Because react-native-health requires custom native code, it cannot be used in the standard Expo Go app. You must use a Development Client or a custom build.

    1. Install the package using npx expo install:
      npx expo install react-native-health
    2. Add the react-native-health config plugin to your app.json or app.config.js plugins array.
    3. Rebuild your native app (e.g., using npx expo prebuild and then building via Xcode/Android Studio, or using EAS Build).
    npx expo install react-native-health