Creating Push Notifications Rapidly With Notifee in React Native (iOS)

Semaphore
8 min readFeb 8, 2024

--

In this article, we delve into the realm of implementing push notifications in React Native with the assistance of Notifee. Notifee stands out as a user-friendly React Native library specifically crafted for seamlessly creating push notifications. Throughout this article, I will walk you through the fundamental steps of leveraging Notifee for this purpose. While our primary emphasis will be on the IOS platform, it’s important to note that the insights gained here are applicable to Android development as well.

Throughout the tutorial, we’ll unravel the intricacies of setting up push notifications, emphasizing a step-by-step approach to harnessing the capabilities of Notifee. By the end, you should have a comprehensive understanding of implementing push notifications within your React Native application, enhancing user engagement and interactivity.

Requirements

To follow along with this article, ensure that you have the following installed on your computer:

  • Node.js v20 (Recommended)
  • Xcode v14 or the latest version

Setting up Dependencies

Assuming you’re well-acquainted with the React Native project creation process, let’s move forward with integrating Notifee into your project. In case you face any challenges setting up a React Native project, refer to this link for assistance.

To install Notifee seamlessly, copy and paste the provided code into your project’s root terminal. This straightforward integration will pave the way for exploring the capabilities of Notifee in enhancing your React Native application with efficient push notification functionalities.

#npm
npm install --save @notifee/react-native

# Yarn
yarn add @notifee/react-native

Once you have successfully installed Notifee, proceed to your IOS folder and execute the following code:

pod install

After successfully installing the pod, locate the “/ios/YourApp.xcworkspace” folder in Finder and double-click on it to build your IOS application. This will open Xcode, where you can click the run button to start the build process for your application. As an additional check, you can run the command npx react-native doctor in your project’s root terminal to confirm if Xcode is installed and correctly configured on your local machine, as illustrated below:

Following a successful build, your IOS simulator (phone) will appear, and a terminal will pop up. Simply press the “i” key on your keyboard to run on IOS. This action will establish a connection between your IOS project and the simulator device, enabling you to view and make changes to your application.

Displaying Basic Notification

In this section, we will showcase a basic notification using our virtual simulator device. Initially, we just need to invoke the Notifee library we installed. The code below provides a comprehensive representation of the code that will trigger the push notification:

import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
import React from "react";
import notifee from "@notifee/react-native";
const App = () => {
async function onTriggerHandler() {
await notifee.displayNotification({
id: "1234",
title: `New notification`,
body: "Greetings! How are you faring today?",
});
}
return (
<View style={styles.body}>
<TouchableOpacity style={styles.button} onPress={onTriggerHandler}>
<Text style={styles.btn_text}>Greet!</Text>
</TouchableOpacity>
</View>
);
};
export default App;const styles = StyleSheet.create({
body: {
backgroundColor: "black",
flex: 1,
justifyContent: "center",
alignItems: "center",
},
button: {
width: 200,
backgroundColor: "hotpink",
padding: 20,
alignItems: "center",
borderRadius: 20,
},
btn_text: {
fontSize: 20,
color: "white",
},
});

Upon executing the provided code, the resulting output will seamlessly appear without any notification. To trigger a notification, click the “Greet!” button, initiating the onTriggerHandler() function, which defines an asynchronous callback. This function employs the notifee.displayNotification() method to showcase a new notification with an exclusive identifier of “1234.” The notification features a title labeled “New notification” and a body conveying the message, “Greetings! How are you faring today?” The corresponding source code for this segment is accessible on GitHub; you can access it by clicking here.

Output:

Sending Multiple Notifications with Unique ID

To create multiple notifications for various purposes, assign a unique ID to each notification. Alternatively, you can generate random numbers if the notifications are not manually called or integrated. In this section, we will illustrate the manual creation of two separate notifications: one for “New Chat Message” and another for “Update App Notification,” each identified by a distinct ID. The provided code snippet demonstrates the process of generating diverse notifications with their corresponding unique identifiers.

import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
import React from "react";
import notifee from "@notifee/react-native";
const App = () => {
async function onTriggerHandler() {
await notifee.displayNotification({
id: "1",
title: `New message in chat`,
body: "You received a new message from Mike.",
});
await notifee.displayNotification({
id: "2",
title: `App update`,
body: "Please update your app from the App Store as it is outdated.",
});
}
return (
<View style={styles.body}>
<TouchableOpacity style={styles.button} onPress={onTriggerHandler}>
<Text style={styles.btn_text}>Display</Text>
</TouchableOpacity>
</View>
);
};
export default App;const styles = StyleSheet.create({
body: {
backgroundColor: "#ddd",
flex: 1,
justifyContent: "center",
alignItems: "center",
justifyContent: "space-around",
},
button: {
width: 200,
backgroundColor: "hotpink",
padding: 20,
alignItems: "center",
borderRadius: 20,
},
btn_text: {
fontSize: 20,
color: "white",
},
});

The aforementioned code is accessible on GitHub for cloning. To examine the details of the implementation, you can view the “App.js” file directly by clicking here.

Output:

Media Attachment

In this section, we will explore the capability of the Notifee library to incorporate media files as attachments in notifications. When a notification with an image is sent, it is presented as a small image on iPhone devices, as depicted below:

Upon expanding or press-holding the notification from the top of the screen, the complete image is revealed, as illustrated below:

The code snippet for implementing this media attachment mechanism is provided below:

notifee.displayNotification({
title: "Penguin bird was uploaded.",
body: "You've been successful in posting your Penguin bird picture online.",
ios: {
attachments: [
{
url: "https://d3bg7r0nxumtp2.cloudfront.net/3d8ff55e27d71d6e47d6f4608eb4b4fa8f52fd22.jpg",
},
],
},
});

The attachment attribute functions as an array of objects, where you can easily utilize the url parameter to include local images from assets or hosted images from the internet. In the example, we have employed an image link from Google. To clone this specific project section from GitHub, kindly use the following link.

Notification Badge Count

The Notifee library offers support for a badge counter in the app, indicating the number of unread notifications on the app icon displayed on the desktop. In this article, I will guide you through the process of adding a badge counter to your application. It’s important to note that the Notifee library doesn’t inherently detect unread notifications, but you can take control of this functionality in your code by manually integrating the number counter.

To set a badge count, use the setBadgeCount function from Notifee, which returns a promise. You can then utilize the .thencallback to log a successful message, as illustrated below:

useEffect(() => {
notifee.setBadgeCount(100).then(() => console.log("Badge count set!"));
}, []);

The output:

To clear the badge count, set the value to 0 using the following code snippet:

notifee.setBadgeCount(0).then(() => console.log("Badge count removed!"));

For further details and access to the code, please visit the GitHub repository by clicking here.

Notification Sound

Notifee extends support for sound on iOS, allowing you to enhance your notifications with auditory cues. The supported sound formats encompass .wav, .aiff, and .caf. You can import sounds from your assets folder or use the default iOS sound. The following snippet illustrates how to incorporate default sound into your Notifee notifications, providing an additional layer of engagement for iOS users:

async function onTriggerHandler() {
notifee.displayNotification({
body: "Custom sound",
ios: {
sound: "default",
},
});
}

The default sound is reminiscent of the iOS notification sound utilized by Twitter. To access this file on GitHub, please click here.

Notification Categories with button

In this segment, we will showcase notifications featuring buttons. The key is to incorporate an action button into a specific notification. For instance, I have crafted a new notification that when press-held, reveals category buttons facilitating actions such as accepting or rejecting a user’s request to join a chat conversation within your application.

To implement the described functionality, we merely need to define the categories that will serve as buttons, along with their respective category IDs. These category IDs can be either strings or numbers, as demonstrated below:

async function setCategories() {
await notifee.setNotificationCategories([
{
id: "action",
actions: [
{
id: "accept",
title: "Accept user",
},
{
id: "reject",
title: "Reject user",
},
],
},
]);
}
setCategories();

Next, we just need to invoke the category by its ID within the displayNotification function in the iOS configuration, as illustrated below:

notifee.displayNotification({
title: "New member request",
body: "Hello Administrator, a new member is interested in participating in the chat discussion.",
ios: {
categoryId: "action",
},
});

You can easily clone the source code for this section on GitHub by clicking here. The output of the above code is displayed below:

If you set destructive to true in the setNotificationCategories configuration, it alters the color of the action, as demonstrated below:

Enabling an input feature within the notification system, permitting users to type directly into notifications, involves adding an “input” property and setting its value to true in the category action object. In my implementation, I specifically included the input property for the accept button. Consequently, clicking on the accept button triggers the appearance of an input field, providing users with the ability to input text directly within the notification, as demonstrated in the example below:

Conclusion

I hope you found this article both enjoyable and informative. We’ve comprehensively covered all the essential steps required to establish push notifications for your device. Furthermore, we delved into diverse push notification mechanisms utilized by other applications in their systems. The GitHub repository for this application is openly accessible, and you can quickly navigate to it by clicking here. Feel free to explore the repository for further insights and resources related to push notifications in React Native with Notifee.

Originally published at https://semaphoreci.com on February 8, 2024.

--

--

Semaphore

Supporting developers with insights and tutorials on delivering good software. · https://semaphoreci.com