Day 6: Sending Push Notifications for Reminders and Daily Goals


#PushNotifications #FitnessGoals #ReactNative

Welcome to Day 6! Today, you’ll implement push notifications in your fitness app to remind users of their daily goals and encourage consistent activity. Notifications are a great way to re-engage users and boost app interaction.


What You’ll Learn Today

  1. Configure Firebase for push notifications.
  2. Set up notification scheduling with React Native.
  3. Test notifications on Android and iOS devices.

Step 1: Configure Firebase for Push Notifications

1. Create a Firebase Project

  1. Go to the Firebase Console.
  2. Create a new project and register your app.
    • For Android: Add the package name (e.g., com.fitnessapp).
    • For iOS: Add the app bundle ID.

2. Download Configuration Files

  • For Android: Download google-services.json and place it in android/app.
  • For iOS: Download GoogleService-Info.plist and add it to your Xcode project.

3. Install Firebase Dependencies

npm install @react-native-firebase/app @react-native-firebase/messaging
npx pod-install

Step 2: Configure Firebase Messaging

1. Android Setup

  • Update android/build.gradle:
buildscript {
    dependencies {
        classpath 'com.google.gms:google-services:4.3.14'
    }
}
  • Update android/app/build.gradle:
apply plugin: 'com.google.gms.google-services'
  • Add permissions to AndroidManifest.xml:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

2. iOS Setup

  • Enable Push Notifications and Background Modes in Xcode:
    • Go to Signing & Capabilities and add Push Notifications.
    • Under Background Modes, check Remote Notifications.
  • Add the following to your AppDelegate.m:
#import <Firebase.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    if ([FIRApp defaultApp] == nil) {
        [FIRApp configure];
    }
    return YES;
}

Step 3: Set Up React Native Messaging

1. Handle Notification Permissions

Create a file NotificationService.js:

import messaging from '@react-native-firebase/messaging';

export const requestUserPermission = async () => {
  const authStatus = await messaging().requestPermission();
  const enabled =
    authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
    authStatus === messaging.AuthorizationStatus.PROVISIONAL;

  if (enabled) {
    console.log('Authorization status:', authStatus);
  }
};

export const getFcmToken = async () => {
  const token = await messaging().getToken();
  console.log('FCM Token:', token);
};

2. Listen for Notifications

Update App.js to listen for foreground and background notifications:

import React, { useEffect } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import { requestUserPermission, getFcmToken } from './NotificationService';

const App = () => {
  useEffect(() => {
    requestUserPermission();
    getFcmToken();

    const unsubscribe = messaging().onMessage(async (remoteMessage) => {
      console.log('Foreground notification received:', remoteMessage.notification);
    });

    return unsubscribe;
  }, []);

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Push Notifications Setup</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  title: { fontSize: 24, fontWeight: 'bold' },
});

export default App;

Step 4: Schedule Notifications

1. Install Notification Library

Use react-native-push-notification for local notifications:

npm install react-native-push-notification
npx pod-install

2. Set Up Notification Configuration

Create a file NotificationScheduler.js:

import PushNotification from 'react-native-push-notification';

export const scheduleDailyReminder = () => {
  PushNotification.localNotificationSchedule({
    channelId: 'fitness-reminders',
    title: 'Daily Fitness Goal',
    message: 'Don’t forget to complete your steps for today!',
    date: new Date(Date.now() + 60 * 1000), // Schedule for 1 minute from now
    repeatType: 'day',
  });
};

// Configure the notification channel (Android only)
PushNotification.createChannel(
  {
    channelId: 'fitness-reminders',
    channelName: 'Fitness Reminders',
    channelDescription: 'Daily fitness goal reminders',
  },
  (created) => console.log(`Channel created: ${created}`) // Check if the channel was created
);

3. Trigger Notification Scheduling

Update App.js:

import { scheduleDailyReminder } from './NotificationScheduler';

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

Step 5: Test Notifications

  1. Foreground Notifications:
    • Run the app: npx react-native run-android npx react-native run-ios
    • Trigger a test notification using the Firebase Console.
  2. Background Notifications:
    • Close the app and trigger a test notification.
    • Ensure the notification appears in the system tray.
  3. Local Notifications:
    • Check if daily reminders are displayed on schedule.
See also  Day 9: Adding User Authentication and Profile Management

Enhance Notifications

  1. Add Action Buttons:
    • Allow users to mark goals as complete or snooze notifications.
  2. Personalize Messages:
    • Include the user’s name or fitness goal in the notification.
  3. Custom Sounds:
    • Use a motivational sound for reminders.

SEO Optimization for This Tutorial

Keywords: React Native push notifications, Firebase notifications setup, fitness app reminders, React Native notification scheduling, fitness goal notifications.

Meta Description: Learn how to implement push notifications in your React Native fitness app. Send daily reminders and engage users with Firebase and local notifications.


Summary

Today, you implemented push notifications in your fitness app, providing users with daily reminders to achieve their goals. This feature keeps users motivated and engaged with your app.

What’s Next: Tomorrow, you’ll learn to store and analyze workout history with graphs.

Stay tuned for Day 7: Storing and Analyzing Workout History.


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.