### Install Package with npm or yarn Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/integration-guide.md Install the package using either npm or yarn. This is the first step for integration. ```bash npm install @ovalmoney/react-native-fitness # or yarn add @ovalmoney/react-native-fitness ``` -------------------------------- ### Get Sleep Analysis Example Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/types.md Demonstrates how to fetch sleep analysis data and iterate through the records to log details like state, duration, and source ID. Ensure the Fitness module is imported. ```javascript const sleep = await Fitness.getSleepAnalysis({ startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-01-31T23:59:59.999Z', }); sleep.forEach(record => { console.log(`${record.sourceName} recorded:`); console.log(` State: ${record.value}`); console.log(` Duration: ${record.startDate} to ${record.endDate}`); console.log(` Source ID: ${record.sourceId}`); }); ``` -------------------------------- ### Get Steps Return Format Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/native-modules.md Example of the expected return format for step count data, including quantity and time range. ```javascript [ { quantity: 8234, startDate: "2024-01-01T00:00:00.000Z", endDate: "2024-01-02T00:00:00.000Z" } ] ``` -------------------------------- ### Get Calories Data Example Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/types.md Retrieves daily calorie data. The returned data includes the start and end dates of the interval and the total calories burned. ```javascript const calories = await Fitness.getCalories({ startDate: '2024-01-01T00:00:00.000Z', interval: 'days', }); // Each element in returned array: // { // startDate: '2024-01-01T00:00:00.000Z', // endDate: '2024-01-02T00:00:00.000Z', // quantity: 2150.75 // } ``` -------------------------------- ### CocoaPods Installation for react-native-fitness Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/configuration.md Include this pod entry in your Podfile for installing the library via CocoaPods. Ensure you run 'pod install' afterwards. ```ruby target 'YourApp' do # ... other pods ... pod 'react-native-fitness', :path => '../node_modules/@ovalmoney/react-native-fitness' end ``` -------------------------------- ### Install with npm Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md Use npm to add the react-native-fitness library to your project dependencies. ```bash npm install @ovalmoney/react-native-fitness --save ``` -------------------------------- ### Manual Android Setup for Native Modules Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/integration-guide.md Configure your android/settings.gradle and android/app/build.gradle files for manual Android linking. Also, update MainApplication.java to include the RNFitnessPackage. ```gradle include ':@ovalmoney_react-native-fitness' project(':@ovalmoney_react-native-fitness').projectDir = new File(rootProject.projectDir, '../node_modules/@ovalmoney/react-native-fitness/android') ``` ```gradle dependencies { compile project(':@ovalmoney_react-native-fitness') } ``` ```java import com.ovalmoney.fitness.RNFitnessPackage; protected List getPackages() { return Arrays.asList( new MainReactPackage(), new RNFitnessPackage() ); } ``` -------------------------------- ### Manual iOS Setup for Native Modules Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/integration-guide.md Configure your Podfile and Xcode for manual iOS linking. Ensure HealthKit capability is added. ```ruby pod 'react-native-fitness', :path => '../node_modules/@ovalmoney/react-native-fitness' ``` ```bash cd ios && pod install && cd .. ``` -------------------------------- ### Request Permissions and Fetch Steps Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/README.md Example of requesting necessary permissions and fetching step data within a specified date range. ```javascript import Fitness from '@ovalmoney/react-native-fitness'; // Request permissions await Fitness.requestPermissions([ { kind: Fitness.PermissionKinds.Steps, access: Fitness.PermissionAccesses.Read } ]); // Fetch data const steps = await Fitness.getSteps({ startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-01-31T23:59:59.999Z', interval: 'days' }); ``` -------------------------------- ### Version Detection Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/configuration.md Examples for checking the operating system version on both iOS and Android. ```APIDOC ### Version Detection For iOS version checks: ```javascript import { Platform } from 'react-native'; if (Platform.OS === 'ios' && Platform.Version >= 12) { // iOS 12+ specific code } ``` For Android API level checks: ```javascript import { NativeModules } from 'react-native'; // Check Android API level at runtime const isAndroidN = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N; ``` ``` -------------------------------- ### Permission Examples Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/types.md Illustrates how to create permission objects for accessing steps or calories data. These are used with functions like isAuthorized() and requestPermissions(). ```javascript const stepsReadPermission = { kind: Fitness.PermissionKinds.Steps, access: Fitness.PermissionAccesses.Read, }; const caloriesWritePermission = { kind: Fitness.PermissionKinds.Calories, access: Fitness.PermissionAccesses.Write, }; ``` -------------------------------- ### Install with Yarn Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md Use Yarn to add the react-native-fitness library to your project dependencies. ```bash yarn add @ovalmoney/react-native-fitness ``` -------------------------------- ### Get Heart Rate Data Example Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/types.md Retrieves hourly heart rate data. Note that on iOS, this uses discrete average calculation, while on Android, it uses heart rate summary aggregation. The returned data includes start and end dates and the average heart rate. ```javascript const heartRates = await Fitness.getHeartRate({ startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-01-02T23:59:59.999Z', interval: 'hour', }); // Each element in returned array: // { // startDate: '2024-01-01T00:00:00.000Z', // endDate: '2024-01-01T01:00:00.000Z', // quantity: 72.5 // } ``` -------------------------------- ### Get Steps Data Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/types.md Retrieves step count data for a specified date range and interval. The returned data includes start date, end date, and the quantity of steps. ```typescript interface StepRecord { startDate: string endDate: string quantity: number } ``` ```javascript const steps = await Fitness.getSteps({ startDate: '2024-01-01T00:00:00.000Z', interval: 'days', }); // Each element in returned array: // { // startDate: '2024-01-01T00:00:00.000Z', // endDate: '2024-01-02T00:00:00.000Z', // quantity: 8234 // } ``` -------------------------------- ### Fitness.getSteps Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md Fetches the number of steps recorded within a specified period. Requires a start date and an end date. The interval can be set to 'hour' or 'minute' for more granular data; otherwise, it defaults to 'days'. An error will be thrown if the start date is not provided. ```APIDOC ## Fitness.getSteps ### Description Fetch steps on a given period of time. ### Method Fitness.getSteps ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **startDate** (string) - Required - The start date for the period (e.g., 'YYYY-MM-DD'). - **endDate** (string) - Required - The end date for the period (e.g., 'YYYY-MM-DD'). - **interval** (string) - Optional - The interval for data granularity. Can be 'hour' or 'minute'. Defaults to 'days'. ### Request Example ```javascript Fitness.getSteps({ startDate: '2023-01-01', endDate: '2023-01-07', interval: 'days' }) ``` ### Response #### Success Response (Object) - **steps** (Array) - An array of objects, each containing step data for the specified interval. - **value** (number) - The number of steps. - **date** (string) - The date or timestamp of the data point. #### Response Example ```json { "steps": [ { "value": 10000, "date": "2023-01-01" }, { "value": 12000, "date": "2023-01-02" } ] } ``` #### Error Response - Throws an error if `startDate` is not provided. ``` -------------------------------- ### Interval Usage Examples Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/types.md Demonstrates fetching health data with different time intervals. Use 'hour' for hourly aggregation and 'minute' for per-minute data points in functions like getSteps() and getHeartRate(). ```javascript // Fetch hourly step data const steps = await Fitness.getSteps({ startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-01-02T23:59:59.999Z', interval: 'hour', }); // Fetch minute-level heart rate data const heartRate = await Fitness.getHeartRate({ startDate: '2024-01-01T00:00:00.000Z', interval: 'minute', }); ``` -------------------------------- ### Sleep Analysis Return Format Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/native-modules.md Example of the expected return format for sleep analysis data, including value, source, and time range. ```javascript [ { value: "ASLEEP", sourceName: "Apple Health", sourceId: "com.apple.health", startDate: "2024-01-01T22:00:00.000Z", endDate: "2024-01-02T06:00:00.000Z" } ] ``` -------------------------------- ### Query Step Count Data from Google Fit Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/native-modules.md Example of how to query step count data from Google Fit. It constructs a DataReadRequest, executes it, and processes the results to extract step data. ```java public void getSteps(Context context, double startDate, double endDate, String customInterval, final Promise promise) { DataSource ESTIMATED_STEP_DELTAS = new DataSource.Builder() .setDataType(DataType.TYPE_STEP_COUNT_DELTA) .setType(DataSource.TYPE_DERIVED) .setStreamName("estimated_steps") .setAppPackageName("com.google.android.gms") .build(); TimeUnit interval = getInterval(customInterval); DataReadRequest readRequest = new DataReadRequest.Builder() .aggregate(ESTIMATED_STEP_DELTAS, DataType.AGGREGATE_STEP_COUNT_DELTA) .bucketByTime(1, interval) .setTimeRange((long) startDate, (long) endDate, TimeUnit.MILLISECONDS) .build(); Fitness.getHistoryClient(context, GoogleSignIn.getLastSignedInAccount(context)) .readData(readRequest) .addOnSuccessListener(dataReadResponse -> { WritableArray steps = Arguments.createArray(); for (Bucket bucket : dataReadResponse.getBuckets()) { for (DataSet dataSet : bucket.getDataSets()) { processStep(dataSet, steps); } } promise.resolve(steps); }) .addOnFailureListener(e -> promise.reject(e)); } ``` -------------------------------- ### Fitness.getCalories Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md Fetches the calories burnt in kilocalories within a specified period. Requires a start date and an end date. The interval can be set to 'hour' or 'minute' for more granular data; otherwise, it defaults to 'days'. An error will be thrown if the start date is not provided. ```APIDOC ## Fitness.getCalories ### Description Fetch calories burnt in kilocalories on a given period of time. ### Method Fitness.getCalories ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **startDate** (string) - Required - The start date for the period (e.g., 'YYYY-MM-DD'). - **endDate** (string) - Required - The end date for the period (e.g., 'YYYY-MM-DD'). - **interval** (string) - Optional - The interval for data granularity. Can be 'hour' or 'minute'. Defaults to 'days'. ### Request Example ```javascript Fitness.getCalories({ startDate: '2023-01-01', endDate: '2023-01-07', interval: 'days' }) ``` ### Response #### Success Response (Object) - **calories** (Array) - An array of objects, each containing calorie data for the specified interval. - **value** (number) - The calories burnt in kilocalories. - **date** (string) - The date or timestamp of the data point. #### Response Example ```json { "calories": [ { "value": 500, "date": "2023-01-01" }, { "value": 650, "date": "2023-01-02" } ] } ``` #### Error Response - Throws an error if `startDate` is not provided. ``` -------------------------------- ### StepRecord Interface Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/README.md Defines the structure for step data records, including start and end dates and the quantity of steps. ```typescript interface StepRecord { startDate: string // ISO 8601 datetime endDate: string // ISO 8601 datetime quantity: number // Steps, meters, kcal, or bpm } ``` -------------------------------- ### Subscribe to Steps Updates (Android) Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md This method is available only on Android and allows subscribing directly to steps data from the Google Fit store. This eliminates the need for Google Fit to be installed on the device. It returns a promise with `true` for a successful subscription and `false` otherwise. ```javascript Fitness.subscribeToSteps() .then((success) => { // Do something }); ``` -------------------------------- ### Test Fetching Steps Data Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/integration-guide.md This example demonstrates how to test the `getSteps` function from the React Native Fitness API. It asserts that the returned data is defined, is an array, and has the expected properties if data exists. ```javascript import Fitness from '@ovalmoney/react-native-fitness'; describe('Fitness API', () => { test('should fetch steps data', async () => { const steps = await Fitness.getSteps({ startDate: '2024-01-01T00:00:00.000Z', }); expect(steps).toBeDefined(); expect(Array.isArray(steps)).toBe(true); if (steps.length > 0) { expect(steps[0]).toHaveProperty('quantity'); expect(steps[0]).toHaveProperty('startDate'); expect(steps[0]).toHaveProperty('endDate'); } }); }); ``` -------------------------------- ### Process Step Data from Google Fit Dataset Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/native-modules.md Helper method to process step data points from a Google Fit DataSet. It extracts start and end times, and the step quantity, formatting them into a WritableMap. ```java private void processStep(DataSet dataSet, WritableArray map) { for (DataPoint dp : dataSet.getDataPoints()) { for(Field field : dp.getDataType().getFields()) { WritableMap stepMap = Arguments.createMap(); stepMap.putString("startDate", dateFormat.format(dp.getStartTime(TimeUnit.MILLISECONDS))); stepMap.putString("endDate", dateFormat.format(dp.getEndTime(TimeUnit.MILLISECONDS))); stepMap.putDouble("quantity", dp.getValue(field).asInt()); map.pushMap(stepMap); } } } ``` -------------------------------- ### Request Fitness Permissions Correctly (iOS) Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/errors.md This snippet shows the correct way to request fitness data permissions, ensuring at least one read permission is included to avoid the `ErrorEmptyPermissions` on iOS. The incorrect example illustrates the error condition. ```javascript // INCORRECT - will throw ErrorEmptyPermissions on iOS try { await Fitness.requestPermissions([ { kind: Fitness.PermissionKinds.Steps, access: Fitness.PermissionAccesses.Write } ]); } catch (error) { console.error('Error:', error); // ErrorEmptyPermissions on iOS } // CORRECT - at least one read permission try { await Fitness.requestPermissions([ { kind: Fitness.PermissionKinds.Steps, access: Fitness.PermissionAccesses.Read }, { kind: Fitness.PermissionKinds.HeartRate, access: Fitness.PermissionAccesses.Write }, ]); } catch (error) { console.error('Error:', error); } ``` -------------------------------- ### getSteps Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/native-modules.md Retrieves the total number of steps within a specified date range and interval. The results are aggregated and returned as an array of objects, each containing the quantity of steps and the start and end dates of the interval. Dates are formatted using ISO8601. ```APIDOC ## getSteps ### Description Retrieves the total number of steps within a specified date range and interval. The results are aggregated and returned as an array of objects, each containing the quantity of steps and the start and end dates of the interval. Dates are formatted using ISO8601. ### Method RCT_REMAP_METHOD ### Parameters #### Path Parameters - `startDate` (double) - Milliseconds since epoch - `endDate` (double) - Milliseconds since epoch - `customInterval` (NSString) - String ('day', 'hour', 'minute') controlling aggregation ### Return Format ```javascript [ { quantity: 8234, startDate: "2024-01-01T00:00:00.000Z", endDate: "2024-01-02T00:00:00.000Z" } ] ``` ``` -------------------------------- ### Get Weekly Steps with TypeScript Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/integration-guide.md Fetches step data for the past week using TypeScript. It defines an interface for step data and handles potential errors during the data retrieval process. ```typescript import Fitness from '@ovalmoney/react-native-fitness'; interface StepData { date: string; steps: number; } async function getWeeklySteps(): Promise { const endDate = new Date(); const startDate = new Date(endDate.getTime() - 7 * 24 * 60 * 60 * 1000); try { const records = await Fitness.getSteps({ startDate: startDate.toISOString(), endDate: endDate.toISOString(), interval: 'days', }); return records.map(record => ({ date: record.startDate.split('T')[0], steps: record.quantity, })); } catch (error) { console.error('Error:', error); return []; } } ``` -------------------------------- ### Handle MethodNotAvailable Error on Android Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/errors.md This example shows how to catch and handle the specific error code -99, which indicates that a method is not available on older Android versions. It checks the platform and provides a fallback or logs a message. ```javascript import { Platform } from 'react-native'; async function getSleepData(startDate, endDate) { if (Platform.OS === 'android') { try { const sleep = await Fitness.getSleepAnalysis({ startDate, endDate }); return sleep; } catch (error) { if (error.message === '-99') { console.log('Sleep analysis not available on Android < 7.0'); return []; } throw error; } } else { return await Fitness.getSleepAnalysis({ startDate, endDate }); } } ``` -------------------------------- ### Fetch Weekly Fitness Data Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/README.md This function retrieves weekly steps, distance, and calories data. It calculates the start and end dates for the past seven days and fetches data concurrently using Promise.all. ```javascript async function getWeeklyData() { const endDate = new Date(); const startDate = new Date(endDate.getTime() - 7 * 24 * 60 * 60 * 1000); const [steps, distance, calories] = await Promise.all([ Fitness.getSteps({ startDate: startDate.toISOString(), endDate: endDate.toISOString(), interval: 'days' }), Fitness.getDistances({ startDate: startDate.toISOString(), endDate: endDate.toISOString(), interval: 'days' }), Fitness.getCalories({ startDate: startDate.toISOString(), endDate: endDate.toISOString(), interval: 'days' }) ]); return { steps, distance, calories }; } ``` -------------------------------- ### Fitness.subscribeToSteps Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md Subscribes to receive step data updates. This method is only available on Android. It allows receiving steps without requiring Google Fit to be installed on the device. Returns a promise with true for a successful subscription and false otherwise. ```APIDOC ## Fitness.subscribeToSteps ### Description Available only on android. Subscribe only to steps from the Google Fit store. It returns a promise with `true` for a successful subscription and `false` otherwise. Call this function to get steps and eliminate the need to have Google Fit installed on the device. ### Method Fitness.subscribeToSteps ### Parameters None ### Request Example ```javascript Fitness.subscribeToSteps() ``` ### Response #### Success Response (boolean) - **subscribed** (boolean) - True for a successful subscription, false otherwise. #### Response Example ```json { "subscribed": true } ``` ``` -------------------------------- ### Get Steps with Graceful Fallbacks Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/integration-guide.md Handles various error codes returned by Fitness.getSteps, including permission issues, no data, invalid dates, and unavailable features. Retries requests after handling specific errors like missing permissions. ```javascript async function getStepsWithFallback(startDate, endDate) { try { // Try to get steps return await Fitness.getSteps({ startDate, endDate, interval: 'days' }); } catch (error) { const code = parseInt(error.message, 10); switch (code) { case -96: // ErrorEmptyPermissions console.warn('Need to request permissions'); await requestPermissions(); return getStepsWithFallback(startDate, endDate); // Retry case -97: // ErrorNoEvents console.log('No data available'); return []; case -98: // ErrorDateNotCorrect console.error('Invalid date format'); return []; case -99: // ErrorMethodNotAvailable console.log('Feature not available on this device'); return []; case -100: // ErrorHKNotAvailable console.error('Health Kit not available'); return []; default: console.error('Unexpected error:', error); return []; } } } ``` -------------------------------- ### Get Distances Data Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/types.md Retrieves distance traveled data for a specified date range and interval. The returned data includes start date, end date, and the quantity of distance in meters. ```typescript interface DistanceRecord { startDate: string endDate: string quantity: number } ``` ```javascript const distances = await Fitness.getDistances({ startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-01-31T23:59:59.999Z', interval: 'hour', }); // Each element in returned array: // { // startDate: '2024-01-01T00:00:00.000Z', // endDate: '2024-01-01T01:00:00.000Z', // quantity: 1200.5 // } ``` -------------------------------- ### Fitness.getSleepAnalysis Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md Fetches sleep analysis data within a specified period. Requires a start date and an end date. An error will be thrown if the start date is not provided. ```APIDOC ## Fitness.getSleepAnalysis ### Description Fetch sleep analysis data on a given period of time. ### Method Fitness.getSleepAnalysis ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **startDate** (string) - Required - The start date for the period (e.g., 'YYYY-MM-DD'). - **endDate** (string) - Required - The end date for the period (e.g., 'YYYY-MM-DD'). ### Request Example ```javascript Fitness.getSleepAnalysis({ startDate: '2023-01-01', endDate: '2023-01-07' }) ``` ### Response #### Success Response (Object) - **sleepAnalysis** (Array) - An array of objects, each containing sleep data for the specified period. - **startTime** (string) - The start time of the sleep period. - **endTime** (string) - The end time of the sleep period. - **duration** (number) - The duration of sleep in minutes. #### Response Example ```json { "sleepAnalysis": [ { "startTime": "2023-01-01T23:00:00Z", "endTime": "2023-01-02T07:00:00Z", "duration": 480 } ] } ``` #### Error Response - Throws an error if `startDate` is not provided. ``` -------------------------------- ### Initialize Fitness API with Permissions Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/configuration.md Safely initializes the Fitness API by requesting necessary read permissions for steps. Includes a check to prevent execution on web platforms. ```javascript import Fitness from '@ovalmoney/react-native-fitness'; import { Platform } from 'react-native'; async function initializeFitness() { try { // Check platform if (Platform.OS === 'web') { console.warn('Fitness API not available on web'); return false; } // Request permissions const permissions = [ { kind: Fitness.PermissionKinds.Steps, access: Fitness.PermissionAccesses.Read } ]; const granted = await Fitness.requestPermissions(permissions); return granted; } catch (error) { console.error('Failed to initialize fitness:', error); return false; } } ``` -------------------------------- ### Fitness.getDistances Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md Fetches the distance traveled in meters within a specified period. Requires a start date and an end date. The interval can be set to 'hour' or 'minute' for more granular data; otherwise, it defaults to 'days'. An error will be thrown if the start date is not provided. ```APIDOC ## Fitness.getDistances ### Description Fetch distance in meters on a given period of time. ### Method Fitness.getDistances ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **startDate** (string) - Required - The start date for the period (e.g., 'YYYY-MM-DD'). - **endDate** (string) - Required - The end date for the period (e.g., 'YYYY-MM-DD'). - **interval** (string) - Optional - The interval for data granularity. Can be 'hour' or 'minute'. Defaults to 'days'. ### Request Example ```javascript Fitness.getDistances({ startDate: '2023-01-01', endDate: '2023-01-07', interval: 'hour' }) ``` ### Response #### Success Response (Object) - **distances** (Array) - An array of objects, each containing distance data for the specified interval. - **value** (number) - The distance in meters. - **date** (string) - The date or timestamp of the data point. #### Response Example ```json { "distances": [ { "value": 5000, "date": "2023-01-01T10:00:00Z" }, { "value": 6500, "date": "2023-01-01T11:00:00Z" } ] } ``` #### Error Response - Throws an error if `startDate` is not provided. ``` -------------------------------- ### Add RNFitnessPackage to MainApplication.java (Android) Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md Import and add the RNFitnessPackage to your Android application's main entry point. ```java import com.ovalmoney.fitness.RNFitnessPackage; // ... inside MainApplication.java @Override protected List getPackages() { return Arrays.asList( new MainReactPackage(), new RNFitnessPackage() ); } ``` -------------------------------- ### JavaScript Entry Point with Date Parsing Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/data-flow.md The main JavaScript entry point for the fitness module. It includes utility functions for date parsing and wrapper functions that ensure dates are converted to milliseconds before being passed to native modules. Native module constants are also re-exported. ```javascript import { NativeModules } from 'react-native'; // Date validation and parsing const parseDate = (date) => { if (!date) throw Error('Date not valid'); const parsed = Date.parse(date); if (Number.isNaN(parsed)) throw Error('Date not valid'); return parsed; // Returns milliseconds }; // Wrapper functions handle date parsing const getSteps = ({ startDate, endDate, interval = 'days' }) => NativeModules.Fitness.getSteps( parseDate(startDate), // Convert to milliseconds parseDate(endDate), // Convert to milliseconds interval ); // Export all methods and native constants export default { ...NativeModules.Fitness, // Constants: Platform, PermissionKinds, etc. getSteps, // Wrapped with date parsing getDistances, // Wrapped with date parsing getCalories, // Wrapped with date parsing getHeartRate, // Wrapped with date parsing getSleepAnalysis, // Wrapped with date parsing }; ``` -------------------------------- ### Fitness.getHeartRate Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md Fetches the heart rate in beats per minute (bpm) within a specified period. Requires a start date and an end date. The interval can be set to 'hour' or 'minute' for more granular data; otherwise, it defaults to 'days'. An error will be thrown if the start date is not provided. ```APIDOC ## Fitness.getHeartRate ### Description Fetch heart rate bpm on a given period of time. ### Method Fitness.getHeartRate ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **startDate** (string) - Required - The start date for the period (e.g., 'YYYY-MM-DD'). - **endDate** (string) - Required - The end date for the period (e.g., 'YYYY-MM-DD'). - **interval** (string) - Optional - The interval for data granularity. Can be 'hour' or 'minute'. Defaults to 'days'. ### Request Example ```javascript Fitness.getHeartRate({ startDate: '2023-01-01', endDate: '2023-01-07', interval: 'minute' }) ``` ### Response #### Success Response (Object) - **heartRate** (Array) - An array of objects, each containing heart rate data for the specified interval. - **value** (number) - The heart rate in bpm. - **date** (string) - The date or timestamp of the data point. #### Response Example ```json { "heartRate": [ { "value": 70, "date": "2023-01-01T10:00:00Z" }, { "value": 75, "date": "2023-01-01T10:01:00Z" } ] } ``` #### Error Response - Throws an error if `startDate` is not provided. ``` -------------------------------- ### Module Registration Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/native-modules.md Details the registration of the native module and its initialization process. ```APIDOC ## Module Registration ### File `android/src/main/java/com/ovalmoney/fitness/RNFitnessModule.java` ### Class `RNFitnessModule extends ReactContextBaseJavaModule` ### Module Name ```java @Override public String getName() { return "Fitness"; } ``` ### Initialization ```java public RNFitnessModule(ReactApplicationContext reactContext) { super(reactContext); feedPermissionsMap(); feedAccessesTypeMap(); feedErrorsMap(); this.manager = new Manager(); reactContext.addActivityEventListener(this.manager); } ``` Initializes permission/access/error maps and registers a `Manager` instance as an activity event listener. ``` -------------------------------- ### SleepAnalysisRequest Parameters Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/types.md Defines the structure for requesting sleep analysis data, requiring both start and end dates. ```APIDOC ## SleepAnalysisRequest Parameters ### Description Query parameters for sleep analysis data with required date range (no interval option). ### Fields #### Path Parameters None #### Query Parameters - **startDate** (string) - Required - ISO 8601 date string; query start time. Error thrown if not provided. - **endDate** (string) - Required - ISO 8601 date string; query end time. Must be provided. ### Request Example ```javascript const sleepRequest = { startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-01-31T23:59:59.999Z', }; // Example usage with a method: // const sleep = await Fitness.getSleepAnalysis(sleepRequest); ``` ### Response (Response details for sleep analysis data) ### Date Format Must be a valid ISO 8601 date string that can be parsed by `Date.parse()`. ``` -------------------------------- ### Perform Batch Fitness Data Requests Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/integration-guide.md Utilize Promise.all for making parallel queries to fetch multiple types of fitness data (steps, distance, calories) concurrently, improving efficiency. ```javascript // Use Promise.all for parallel queries const [steps, distance, calories] = await Promise.all([ Fitness.getSteps(params), Fitness.getDistances(params), Fitness.getCalories(params), ]); ``` -------------------------------- ### Include Library in settings.gradle (Android) Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md Add the library's project directory to your Android project's settings.gradle file. ```gradle include ':@ovalmoney_react-native-fitness' project(':@ovalmoney_react-native-fitness').projectDir = new File(rootProject.projectDir, '../node_modules/@ovalmoney/react-native-fitness/android') ``` -------------------------------- ### Get Health Provider Information Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/configuration.md Retrieve the current health provider ('AppleHealth' or 'GoogleFit') using the Fitness.Platform constant. ```javascript import Fitness from '@ovalmoney/react-native-fitness'; console.log(Fitness.Platform); // 'AppleHealth' on iOS, 'GoogleFit' on Android ``` -------------------------------- ### Module Initialization Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/native-modules.md Initializes the native module by setting up permission, access, and error maps, and registering an instance of the Manager class as an activity event listener. This ensures the module is ready to handle activity-related events. ```java public RNFitnessModule(ReactApplicationContext reactContext) { super(reactContext); feedPermissionsMap(); feedAccessesTypeMap(); feedErrorsMap(); this.manager = new Manager(); reactContext.addActivityEventListener(this.manager); } ``` -------------------------------- ### Project File Structure Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/README.md Overview of the directory structure for the react-native-fitness library, detailing the placement of JavaScript wrappers, native iOS and Android code, and configuration files. ```tree @ovalmoney/react-native-fitness/ ├── js/ # JavaScript wrapper │ ├── index.js # Entry point, date parsing │ └── index.d.ts # TypeScript definitions ├── ios/ # iOS native code │ └── RCTFitness/ │ ├── RCTFitness.m # Main module │ ├── RCTFitness+Errors.m │ ├── RCTFitness+Permissions.m │ └── RCTFitness+Utils.m ├── android/ # Android native code │ └── src/main/java/com/ovalmoney/fitness/ │ ├── RNFitnessModule.java │ ├── RNFitnessPackage.java │ └── manager/ │ ├── Manager.java │ └── FitnessError.java └── package.json # Entry: ./js/index.js ``` -------------------------------- ### Link with react-native link Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md Automatically link the library to your React Native project. ```bash react-native link @ovalmoney/react-native-fitness ``` -------------------------------- ### CaloriesRecord Interface Definition Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/types.md Defines the structure for a single calories burned data point, including start and end dates and the quantity of calories. ```typescript interface CaloriesRecord { startDate: string endDate: string quantity: number } ``` -------------------------------- ### Integrate RNFitnessPackage into MainApplication.java Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/configuration.md Add the `RNFitnessPackage` to the list of packages in your `MainApplication.java` file. This makes the library's native functionality available to your React Native app. ```java import com.ovalmoney.fitness.RNFitnessPackage; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new DefaultReactNativeHost(this) { @Override protected List getPackages() { return Arrays.asList( new MainReactPackage(), new RNFitnessPackage() // Add this line ); } }; // ... rest of implementation } ``` -------------------------------- ### Access Fitness Constants Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/README.md Demonstrates how to access various constants provided by the Fitness library for platform identification, permission types, and error codes. ```javascript Fitness.Platform // 'AppleHealth' or 'GoogleFit' Fitness.PermissionKinds // { Steps: 0, Distances: 1, ... } Fitness.PermissionAccesses // { Read: 0, Write: 1 } Fitness.Errors // { hkNotAvailable: -100, ... } ``` -------------------------------- ### HeartRateRecord Interface Definition Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/types.md Defines the structure for a single heart rate data point, including start and end dates and the average heart rate quantity. ```typescript interface HeartRateRecord { startDate: string endDate: string quantity: number } ``` -------------------------------- ### Fetch Steps Data Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md Retrieve step count data for a specified period. The `startDate` is mandatory. The `interval` parameter can be set to 'hour' or 'minute' for more detailed data; otherwise, it defaults to 'days'. ```javascript Fitness.getSteps({ startDate: '2023-01-01', endDate: '2023-01-02', interval: 'days' }) .then((steps) => { // Do something }); ``` -------------------------------- ### Get Sleep Analysis (Android N+) Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/native-modules.md Retrieves sleep sessions from all apps for a specified date range on Android N+. Requires API 24 or higher. ```java @RequiresApi(api = Build.VERSION_CODES.N) public void getSleepAnalysis(Context context, double startDate, double endDate, final Promise promise) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N) { promise.reject(String.valueOf(FitnessError.ERROR_METHOD_NOT_AVAILABLE), "Method not available"); return; } SessionReadRequest request = new SessionReadRequest.Builder() .readSessionsFromAllApps() .read(DataType.TYPE_ACTIVITY_SEGMENT) .setTimeInterval((long) startDate, (long) endDate, TimeUnit.MILLISECONDS) .build(); Fitness.getSessionsClient(context, account) .readSession(request) .addOnSuccessListener(response -> { List sleepSessions = response.getSessions() .stream() .filter(s -> s.getActivity().equals(FitnessActivities.SLEEP)) .collect(Collectors.toList()); WritableArray sleep = Arguments.createArray(); for (Object session : sleepSessions) { List dataSets = response.getDataSet((Session) session); for (DataSet dataSet : dataSets) { processSleep(dataSet, (Session) session, sleep); } } promise.resolve(sleep); }); } ``` -------------------------------- ### Add Pod to Podfile (iOS) Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md Include the library in your iOS project's Podfile for dependency management. ```ruby pod 'react-native-fitness', :path => '../node_modules/@ovalmoney/react-native-fitness' ``` -------------------------------- ### Get Distances Data Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/native-modules.md Retrieves cumulative distance data (walking/running) within a specified date range and interval. Similar to getSteps but uses distance units. ```objc RCT_REMAP_METHOD(getDistances, withStartDate: (double) startDate andEndDate: (double) endDate andInterval: (NSString *) customInterval withDistanceResolver:(RCTPromiseResolveBlock)resolve andDistanceRejecter:(RCTPromiseRejectBlock)reject) ``` -------------------------------- ### Optimal Data Fetching: Single Day, Hour Aggregation Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/data-flow.md Use this pattern for fast queries by requesting a single day's data with hourly aggregation. This results in a small number of data buckets. ```javascript await Fitness.getSteps({ startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-01-02T00:00:00.000Z', interval: 'hour' }); ``` -------------------------------- ### SleepAnalysisRecord Interface Definition Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/types.md Defines the structure for a single sleep session or sleep state data point, including start and end times, value, and source information. ```typescript interface SleepAnalysisRecord { startDate: string endDate: string value: number | string sourceName: string sourceId: string } ``` -------------------------------- ### Get Calories Data Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/native-modules.md Retrieves cumulative active energy burned data within a specified date range and interval. Similar to getSteps but uses kilocalorie units. ```objc RCT_REMAP_METHOD(getCalories, withStartDate: (double) startDate andEndDate: (double) endDate andInterval: (NSString *) customInterval withCaloriesResolver:(RCTPromiseResolveBlock)resolve andCaloriesRejecter:(RCTPromiseRejectBlock)reject) ``` -------------------------------- ### Import and Access Fitness Methods and Constants Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/configuration.md Import the default Fitness object to access its public methods like isAuthorized, requestPermissions, and getSteps, as well as constants such as Platform, PermissionKinds, PermissionAccesses, and Errors. ```javascript import Fitness from '@ovalmoney/react-native-fitness'; // Access methods Fitness.isAuthorized() Fitness.requestPermissions() Fitness.getSteps() // Access constants Fitness.Platform Fitness.PermissionKinds Fitness.PermissionAccesses Fitness.Errors ``` -------------------------------- ### Fetch Heart Rate Data Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/api-reference.md Retrieves heart rate data for a specified date range with an optional interval. Use this to get aggregated heart rate information. ```javascript import Fitness from '@ovalmoney/react-native-fitness'; try { const heartRates = await Fitness.getHeartRate({ startDate: '2024-01-01T00:00:00.000Z', endDate: '2024-01-02T23:59:59.999Z', interval: 'hour', }); const avgHR = heartRates.reduce((sum, r) => sum + r.quantity, 0) / heartRates.length; console.log(`Average heart rate: ${avgHR} bpm`); } catch (error) { console.error('Error fetching heart rate:', error); } ``` -------------------------------- ### JavaScript Configuration and Methods Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/configuration.md The library exports a default object with all public methods and constants. These can be accessed directly after importing the library. ```APIDOC ## JavaScript Configuration ### Default Export The library exports a default object with all public methods and constants: ```javascript import Fitness from '@ovalmoney/react-native-fitness'; // Access methods Fitness.isAuthorized() Fitness.requestPermissions() Fitness.getSteps() // Access constants Fitness.Platform Fitness.PermissionKinds Fitness.PermissionAccesses Fitness.Errors ``` ### No Runtime Options Unlike many libraries, react-native-fitness does not accept constructor options or configuration objects. All configuration is platform-specific and set at build time. ``` -------------------------------- ### Get Steps Data Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/native-modules.md Retrieves cumulative step count data within a specified date range and interval. Requires startDate, endDate, and a customInterval ('day', 'hour', 'minute'). ```objc RCT_REMAP_METHOD(getSteps, withStartDate: (double) startDate andEndDate: (double) endDate andInterval: (NSString *) customInterval withStepsResolver:(RCTPromiseResolveBlock)resolve andStepsRejecter:(RCTPromiseRejectBlock)reject) ``` -------------------------------- ### subscribeToSteps Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/api-reference.md Subscribe to step count updates from Google Fit (Android only). This enables receiving step data directly from Google Fit without requiring the Google Fit app to be installed. ```APIDOC ## subscribeToSteps ### Description Subscribe to step count updates from Google Fit (Android only). This enables receiving step data directly from Google Fit without requiring the Google Fit app to be installed. ### Method ```typescript subscribeToSteps(): Promise ``` ### Parameters None ### Request Example ```javascript Fitness.subscribeToSteps(); ``` ### Response #### Success Response (200) - **boolean** - Resolves to `true` if subscription successful, `false` otherwise #### Response Example ```json true ``` ### Platform Support - iOS: No-op (not implemented) - Android: All versions ``` -------------------------------- ### Subscribe to Step Count Updates Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/api-reference.md Subscribes to real-time step count updates from Google Fit on Android. This enables receiving step data without the Google Fit app installed. ```javascript import Fitness from '@ovalmoney/react-native-fitness'; try { const subscribed = await Fitness.subscribeToSteps(); if (subscribed) { console.log('Successfully subscribed to steps'); } } catch (error) { console.error('Error subscribing to steps:', error); } ``` -------------------------------- ### Native Module Implementation (iOS/Android) Source: https://github.com/ovalmoney/react-native-fitness/blob/master/_autodocs/data-flow.md Shows the native side implementation for handling the getSteps request on both iOS and Android. It details the creation of health store queries, execution, and result formatting. ```plaintext iOS: RCTFitness.m - getSteps:andEndDate:andInterval:... Creates HKStatisticsCollectionQuery Executes query against HKHealthStore Formats results as NSArray of NSDictionary Android: RNFitnessModule.java - getSteps(...) Calls Manager.getSteps() Creates DataReadRequest Queries Fitness.getHistoryClient().readData() Formats results as WritableArray/WritableMap ↓ On Success Convert to JavaScript-compatible format Resolve promise with results ↓ On Error Reject promise with error code and message ``` -------------------------------- ### Add Dependency to app/build.gradle (Android) Source: https://github.com/ovalmoney/react-native-fitness/blob/master/README.md Include the library as a project dependency in your app's build.gradle file. ```gradle compile project(':@ovalmoney_react-native-fitness') ```