react-native-fitness

repository·master·Indexed 18 days ago

https://github.com/ovalmoney/react-native-fitness

A cross-platform React Native library providing access to Apple HealthKit on iOS and Google Fit on Android. It allows developers to read health metrics including steps, distance, calories, heart rate, and sleep analysis, and includes Android-specific methods for managing Google Fit connections such as logout, disconnect, and step subscription.

Tokens
1.9K
Snippets
7
Records
11
Agent score
13%

What's inside @ovalmoney/react-native-fitness

  1. Install @ovalmoney/react-native-fitness

    master

    Install the package using npm or yarn:

    npm install @ovalmoney/react-native-fitness --save
    # or
    yarn add @ovalmoney/react-native-fitness

    For automatic linking in React Native, run:

    react-native link @ovalmoney/react-native-fitness
    npm install @ovalmoney/react-native-fitness --save
  2. Configure iOS Installation (Manual/Pods)

    master

    If automatic linking fails, follow these steps for iOS:

    Using Pods

    1. Add the following to your Podfile:
      pod 'react-native-fitness', :path => '../node_modules/@ovalmoney/react-native-fitness'
    2. Run pod install in your iOS project directory.
    3. In Xcode, go to Build PhasesLink Binary With Libraries and add libreact-native-fitness.a.
    4. Add the following to your Info.plist to request permissions:
      <key>NSHealthShareUsageDescription</key>
      <string>Read and understand health data.</string>
    5. Crucial: Enable Health Kit in the Capabilities tab in Xcode.

    Manual Xcode Integration

    1. In Xcode's project navigator, right-click LibrariesAdd Files to [your project's name].
    2. Navigate to node_modules/@ovalmoney/react-native-fitness and select RNFitness.xcodeproj.
    3. In Xcode, go to Build PhasesLink Binary With Libraries and add libRNFitness.a.
    pod 'react-native-fitness', :path => '../node_modules/@ovalmoney/react-native-fitness'
  3. Configure Android Installation

    master

    Follow these steps to integrate with Android:

    1. Google Fit Setup: Obtain an OAuth 2.0 Client ID from the Google Fit developer guide.
    2. MainApplication.java:
      • Add import com.ovalmoney.fitness.RNFitnessPackage; at the top.
      • Add new RNFitnessPackage() to the list returned by getPackages().
    3. settings.gradle: Append these lines to android/settings.gradle:
      include ':@ovalmoney_react-native-fitness'
      project(':@ovalmoney_react-native-fitness').projectDir = new File(rootProject.projectDir, '../node_modules/@ovalmoney/react-native-fitness/android')
    4. app/build.gradle: Add this to the dependencies block:
      compile project(':@ovalmoney_react-native-fitness')
    5. build.gradle (Optional): To manage versions, add this to your android/build.gradle:
        fitnessPlayServices: "<Your version>" // default: 17.0.0
        authPlayServices: "<Your version>" // default: 17.0.0
      }
    include ':@ovalmoney_react-native-fitness'
    project(':@ovalmoney_react-native-fitness').projectDir = new File(rootProject.projectDir, '../node_modules/@ovalmoney/react-native-fitness/android')
  4. Fetch Health Data (Steps, Distance, Calories, Heart Rate, Sleep)

    master

    Use the following methods to retrieve health metrics for a specific time period. All methods require a startDate and endDate as strings within an options object.

    • Fitness.getSteps({ startDate, endDate, interval }): Returns step count.
    • Fitness.getDistances({ startDate, endDate, interval }): Returns distance in meters.
    • Fitness.getCalories({ startDate, endDate, interval }): Returns calories burnt in kilocalories.
    • Fitness.getHeartRate({ startDate, endDate, interval }): Returns heart rate in bpm.
    • Fitness.getSleepAnalysis({ startDate, endDate }): Returns sleep analysis data.

    Interval Option: For methods supporting interval, you can set it to 'hour', 'minute', or leave it blank to default to 'days'.

  5. Request and Check Health Permissions

    master

    Before reading health data, you must check or request permissions. Permissions are defined as an array of objects with kind and access keys.

    Note for iOS: At least one permission with Read access must be provided, otherwise errorEmptyPermissions will be thrown. On iOS, requestPermissions always returns true due to Apple's privacy model.

    Note for Android: isAuthorized and requestPermissions work on Android and iOS >= 12.0. On iOS < 12.0, isAuthorized returns an error.

    import Fitness from '@ovalmoney/react-native-fitness';
    
    const permissions = [
      { kind: Fitness.PermissionKinds.Steps, access: Fitness.PermissionAccesses.Write },
    ];
    
    Fitness.isAuthorized(permissions)
      .then((authorized) => {
        // Handle authorization status
      })
      .catch((error) => {
        // Handle error
      });
  6. Manage Google Fit Connection (Android Only)

    master

    The following methods are exclusive to Android and interact with the Google Fit account:

    • Fitness.logout(): Performs a logout from the Google account. Returns true if successful, false if the user cancels.
    • Fitness.disconnect(): Performs a disconnect action from Google Fit. Returns true if successful, false if the user cancels.
    • Fitness.subscribeToSteps(): Subscribes to steps from the Google Fit store. Returns a promise that resolves to true on success. Using this allows you to get steps without requiring the Google Fit app to be installed on the device.
  7. Reference: Error Codes

    master

    The library throws specific error strings when operations fail.

    iOS Errors:

    • hkNotAvailable: HealthKit is not available.
    • methodNotAvailable: isAuthorized called on iOS < 12.0.
    • dateNotCorrect: Received date is invalid.
    • errorEmptyPermissions: No read permissions were provided.
    • errorNoEvents: Error occurred while retrieving data.

    Android Errors:

    • methodNotAvailable: getSleepAnalysis called on Android version less than N.
  8. Retrieve fitness data with getSteps, getDistances, getCalories, and getHeartRate

    master

    You can retrieve various fitness metrics over a specific time range and interval. These methods accept an object with the following properties:

    • startDate: A valid date string or object.
    • endDate: A valid date string or object.
    • interval (optional): The granularity of the data. Defaults to "days".

    Available methods:

    • getSteps({ startDate, endDate, interval })
    • getDistances({ startDate, endDate, interval })
    • getCalories({ startDate, endDate, interval })
    • getHeartRate({ startDate, endDate, interval })
    import Fitness from 'react-native-fitness';
    
    const data = await Fitness.getSteps({
      startDate: '2023-01-01',
      endDate: '2023-01-07',
      interval: 'days'
    });
  9. Retrieve sleep data with getSleepAnalysis

    master

    Use getSleepAnalysis to retrieve sleep-related data for a specific period.

    Arguments:

    • startDate: A valid date string or object.
    • endDate: A valid date string or object.
    import Fitness from 'react-native-fitness';
    
    const sleepData = await Fitness.getSleepAnalysis({
      startDate: '2023-01-01T00:00:00Z',
      endDate: '2023-01-02T00:00:00Z'
    });
  10. Manage Google Fit connection with logout and disconnect

    master

    The library provides methods to manage the Google Fit connection on Android. On iOS, these methods are no-ops (return null).

    • logout(): Logs out from the current Google Account.
    • disconnect(): Disconnects Google Fit.
    import Fitness from 'react-native-fitness';
    
    // Android only
    await Fitness.logout();
    await Fitness.disconnect();