Day 2: Tracking Steps and Displaying Real-Time Data


#StepTracking #FitnessAppDevelopment #GoogleFit

Welcome to Day 2! Today, you’ll learn how to track step counts and display real-time data in your fitness app. This is one of the most essential features for any fitness tracker, allowing users to monitor their physical activity.


What You’ll Learn Today

  1. Retrieve step data from Google Fit and Apple HealthKit.
  2. Display step counts in real-time.
  3. Build a UI to show live fitness data.

Step 1: Retrieve Step Data

1. Get Steps from Google Fit

Update GoogleFitSetup.js to include a function for fetching step data:

import GoogleFit from 'react-native-google-fit';

export const fetchGoogleFitSteps = async () => {
  const options = {
    startDate: new Date(new Date().setHours(0, 0, 0, 0)).toISOString(), // Start of the day
    endDate: new Date().toISOString(), // Current time
  };

  const stepData = await GoogleFit.getDailyStepCountSamples(options);

  const steps = stepData.find(
    (source) => source.source === 'com.google.android.gms:estimated_steps'
  );

  return steps ? steps.steps[0].value : 0;
};

2. Get Steps from Apple HealthKit

Update HealthKitSetup.js to fetch step data:

import AppleHealthKit from 'react-native-health';

export const fetchHealthKitSteps = async () => {
  const options = {
    startDate: new Date(new Date().setHours(0, 0, 0, 0)).toISOString(), // Start of the day
  };

  return new Promise((resolve, reject) => {
    AppleHealthKit.getStepCount(options, (error, results) => {
      if (error) {
        console.error('Error fetching steps from HealthKit', error);
        reject(error);
      } else {
        resolve(results.value);
      }
    });
  });
};

Step 2: Update App.js to Display Step Data

1. Integrate Step Data Retrieval

Update App.js:

import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, Platform } from 'react-native';
import { fetchGoogleFitSteps } from './GoogleFitSetup';
import { fetchHealthKitSteps } from './HealthKitSetup';

const App = () => {
  const [steps, setSteps] = useState(0);

  const fetchSteps = async () => {
    if (Platform.OS === 'android') {
      const stepCount = await fetchGoogleFitSteps();
      setSteps(stepCount);
    } else if (Platform.OS === 'ios') {
      const stepCount = await fetchHealthKitSteps();
      setSteps(stepCount);
    }
  };

  useEffect(() => {
    fetchSteps();
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Step Tracker</Text>
      <Text style={styles.steps}>Steps Today: {steps}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  steps: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
});

export default App;

2. Add Real-Time Updates

Use a polling mechanism to update steps every minute:

useEffect(() => {
  fetchSteps();
  const interval = setInterval(fetchSteps, 60000); // Update every minute
  return () => clearInterval(interval);
}, []);

Step 3: Test Real-Time Step Tracking

  1. Run the app: npx react-native run-android npx react-native run-ios
  2. Simulate Step Data:
    • For Google Fit:
      • Open the Google Fit app on your Android device and manually add steps for testing.
    • For Apple HealthKit:
      • Open the Health app on your iOS device and add steps to “Steps” under “Health Data.”
  3. Verify the Step Count:
    • The step count should update in the app in real-time.
    • Ensure the console logs show accurate data retrieval.
See also  Building a Simple Chatbot with PHP

Step 4: Enhance the UI

1. Add Styling

Update the steps style in App.js for a better user experience:

steps: {
    fontSize: 32,
    fontWeight: 'bold',
    color: '#4caf50',
    marginTop: 20,
},

2. Display a Progress Bar

Install and use the react-native-progress package:

npm install react-native-progress

Add a progress bar to the UI:

import * as Progress from 'react-native-progress';

const dailyGoal = 10000; // Example daily step goal

return (
  <View style={styles.container}>
    <Text style={styles.title}>Step Tracker</Text>
    <Text style={styles.steps}>Steps Today: {steps}</Text>
    <Progress.Bar
      progress={steps / dailyGoal}
      width={200}
      color="#4caf50"
      style={{ marginTop: 20 }}
    />
  </View>
);

SEO Optimization for This Tutorial

Keywords: Step tracking React Native, Google Fit step tracking, Apple HealthKit steps, real-time fitness data, fitness app step count.

Meta Description: Learn how to track steps and display real-time fitness data using Google Fit and Apple HealthKit in a React Native app. Step-by-step guide with code examples.


Summary

Today, you successfully integrated step tracking into your app, fetching and displaying real-time step data using Google Fit and Apple HealthKit APIs.

What’s Next: Tomorrow, you’ll build a UI for daily goals and achievements, giving users a visual representation of their fitness progress.

Stay tuned for Day 3: Building a UI for Daily Goals and Achievements.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.