Day 9: Adding Push Notifications to Your App


In this tutorial, you’ll learn how to integrate push notifications in your React Native app using Expo Notifications. Push notifications can be used to alert users of updates, reminders, or important events. By the end of today’s tutorial, you’ll be able to send, schedule, and handle push notifications in your app.


What You Will Learn Today:

  1. Setting up Expo Notifications
  2. Requesting user permissions for notifications
  3. Sending local notifications
  4. Scheduling notifications
  5. Handling notification events (when users interact with notifications)

Step 1: Installing Expo Notifications

Expo provides a convenient API for handling push notifications. Let’s install the expo-notifications library.

  1. Open your terminal and run the following command:
expo install expo-notifications

This will install the expo-notifications package in your app.


Step 2: Setting Up Notifications

We need to set up notifications by requesting permission from the user to send notifications. Modify your App.js to initialize notifications and request permission:

import React, { useEffect } from 'react';
import * as Notifications from 'expo-notifications';
import { Button, View, Platform, Alert, StyleSheet } from 'react-native';

// Configure how notifications will be displayed when they are received
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});

export default function App() {
  useEffect(() => {
    // Request permission to send notifications
    const requestPermissions = async () => {
      const { status } = await Notifications.requestPermissionsAsync();
      if (status !== 'granted') {
        Alert.alert('Permission not granted for notifications!');
      }
    };

    requestPermissions();
  }, []);

  return (
    <View style={styles.container}>
      <Button title="Send Notification" onPress={sendNotification} />
    </View>
  );
}

const sendNotification = async () => {
  await Notifications.scheduleNotificationAsync({
    content: {
      title: 'New Notification!',
      body: 'This is a local notification.',
    },
    trigger: { seconds: 5 }, // Notification will appear after 5 seconds
  });
};

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

Explanation:

  • Notifications.requestPermissionsAsync(): Requests permission from the user to send notifications. If the user denies the request, we show an alert.
  • setNotificationHandler: Configures how notifications should behave (e.g., whether they should show an alert, play a sound, or set a badge).
  • scheduleNotificationAsync: Schedules a local notification that will be sent after 5 seconds. When the button is pressed, a notification will be scheduled.
See also  Day 8: Storing Data Locally Using AsyncStorage

Step 3: Testing Push Notifications on Your Device

Expo allows you to test push notifications on a physical device. Here’s how:

  1. Run the app using npm start or expo start.
  2. Open the Expo Go app on your mobile device.
  3. Press the Send Notification button, and after 5 seconds, you should see a notification appear on your device.

If you’re using a simulator/emulator, keep in mind that notifications don’t work in all simulators (iOS notifications, for example, must be tested on a physical device).


Step 4: Scheduling Notifications

In addition to sending notifications immediately, you can schedule notifications to be delivered at a specific time or interval. This is useful for reminders, alarms, or notifications that recur over time.

Let’s modify the app to schedule a notification for a specific time in the future.

Modify the sendNotification function to schedule a notification for 1 minute in the future:

const sendNotification = async () => {
  const triggerDate = new Date(Date.now() + 60 * 1000); // 1 minute from now
  await Notifications.scheduleNotificationAsync({
    content: {
      title: 'Scheduled Notification!',
      body: 'This notification was scheduled 1 minute ago.',
    },
    trigger: {
      date: triggerDate,
    },
  });
};

Explanation:

  • trigger: { date }: Specifies a date and time in the future when the notification should be triggered. In this case, we set it for 1 minute from the current time.

Step 5: Handling Notification Interactions

You can handle what happens when users interact with notifications (e.g., tap on a notification to open the app).

  1. Add the following code to App.js to handle notification responses:
useEffect(() => {
  const subscription = Notifications.addNotificationResponseReceivedListener((response) => {
    console.log('User interacted with the notification:', response);
    Alert.alert('Notification Interaction', 'User tapped the notification');
  });

  return () => subscription.remove(); // Clean up the subscription on unmount
}, []);

Explanation:

  • addNotificationResponseReceivedListener: Listens for user interaction with the notification. When the user taps on a notification, this listener will trigger, and you can handle the event as needed (e.g., navigate to a specific screen).
  • In this example, we display an alert when the notification is tapped.
See also  Building a Simple Chatbot with PHP

Step 6: Push Notifications with Expo Push Notifications API

While local notifications are useful, real-world apps often need to send push notifications from a server to users. Expo provides a Push Notifications API that allows you to send notifications from a server to your app users.

Steps to Get Push Notifications Working:

  1. Obtain an Expo Push Token: Every device running your app will have a unique push token that identifies it. You can obtain this token and use it to send notifications to the device from a server.
const getPushToken = async () => {
  const token = await Notifications.getExpoPushTokenAsync();
  console.log('Expo Push Token:', token.data);
};

Add the getPushToken call in the useEffect hook in App.js to retrieve and display the token.

  1. Send Push Notification from Expo’s Push API:
  • Use the Expo Push Notification tool: Expo Push Notification Tool
  • You can send notifications to the device using the Expo Push Token retrieved from the app.

To send a push notification, you would use the Expo Push API from a server or another backend service. Here’s an example of how you would do that:

curl -X POST https://exp.host/--/api/v2/push/send \
  -H "Content-Type: application/json" \
  -d '{
    "to": "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
    "title":"New Message",
    "body": "You've got a new message!"
  }'

Step 7: Recap and Summary

Today, you learned how to send and handle push notifications in a React Native app. Here’s a quick summary of what you’ve done:

  • Installed and set up Expo Notifications.
  • Requested permission from the user to send notifications.
  • Sent and scheduled local notifications.
  • Handled user interactions with notifications (e.g., when a user taps on a notification).
  • Learned how to send push notifications from a server using the Expo Push Notifications API.
See also  Day 5: Using IndexedDB for Local Data Storage

With push notifications, you can now engage users outside of your app, notifying them about important updates, events, or reminders.


Next Up: Day 10 – Deploying Your App

In Day 10, we’ll cover the final step in this tutorial series: deploying your app. You’ll learn how to build and distribute your app to the Google Play Store and Apple App Store.

Stay tuned for the final steps to get your app into the hands of real users!


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.