React Native Setup
Send push notifications to your React Native app with Pushy.
At any time, you may refer to our React Native demo project for a working demo.
Create an App
Sign up for Pushy Trial to get started, or log in to your existing account
Note: No credit card needed. Upgrade to the Pro plan when you're ready by visiting the Billing page.
Create an app and fill in the Android Package Name & iOS Bundle ID:
Please ensure the Android Package Name & iOS Bundle ID you enter precisely match the ones configured in your project files, as they are used to automatically link your client apps with the Pushy Dashboard app having the same Android Package Name & iOS Bundle ID.
Note: If you have already created an app in the Pushy Dashboard for another platform, simply configure your existing dashboard app with your Android Package Name & iOS Bundle ID in the App Settings tab and proceed to the next step.
Click Create and proceed to the next step.
Install the SDK
Run the following command in the root directory of your project to install the pushy-react-native package from npm:
npm install pushy-react-native --save
Run the following command to install the PushyRN
Cocoapods dependency:
cd ios && bundle exec pod install
Enable Push Capability (iOS)
Enable the Push Notifications
capability manually for your iOS app to register for and receive push notifications.
Open your React Native iOS app in Xcode by running the following command in your project ios/
folder:
open *.xcworkspace
Then, visit the project editor, select the Capabilities tab, and turn on the Push Notifications
capability:
Note: Xcode should display two checkmarks indicating that the capability was successfully enabled.
Modify AppDelegate.mm (iOS)
Initialize the plugin by adding the following line to your ios/app/AppDelegate.mm
file, anywhere inside your app's didFinishLaunchingWithOptions
method:
// Initialize Pushy Module
[PushyModule didFinishLaunchingWithOptions:launchOptions];
Make sure to add the required import statement outside of the #if RCT_NEW_ARCH_ENABLED
conditional:
#import <PushyModule.h>
You may close the Xcode project now.
Import Android SDK
Import version 1.0.119
of the Pushy Android SDK and version 1.0.21
of our React Native SDK by adding the following dependencies to your android/app/build.gradle
, within the dependencies {}
declaration:
// Pushy SDK for Android
implementation 'me.pushy:sdk:1.0.119'
// Pushy SDK for React Native Android
implementation 'me.pushy:sdk-react-native:1.0.21'
Please ensure mavenCentral()
is present in your Gradle repositories
section.
Alternatively, download sdk-1.0.119.jar and sdk-react-native-1.0.21.jar and include them manually. If you're interested, check out the SDK changelog to see what's new in the latest version of the Pushy Android SDK.
Load the native PushyPackage
within your MainApplication.kt
class by adding this line of code within the getPackages()
method implementation:
add(me.pushy.sdk.react.PushyPackage());
Modify AndroidManifest
Add the following lines to your android/app/src/main/AndroidManifest.xml
, inside the <manifest>
tag:
<!-- Pushy Permissions -->
<!-- Remove the INTERNET permission if already declared -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<!-- End Pushy Permissions -->
You should manually omit any permission declarations that your app already asks for.
Additionally, add the following declarations inside the <application>
tag:
<!-- Pushy Declarations -->
<!-- Pushy Notification Receiver -->
<!-- Do not modify - internal BroadcastReceiver that forwards notifications to the internal notification service-->
<receiver android:name="me.pushy.sdk.react.receivers.PushReceiver" android:exported="false">
<intent-filter>
<!-- Do not modify this -->
<action android:name="pushy.me" />
</intent-filter>
</receiver>
<!-- Pushy Update Receiver -->
<!-- Do not modify - internal BroadcastReceiver that restarts the listener service -->
<receiver android:name="me.pushy.sdk.receivers.PushyUpdateReceiver" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
<!-- Pushy Boot Receiver -->
<!-- Do not modify - internal BroadcastReceiver that restarts the listener service -->
<receiver android:name="me.pushy.sdk.receivers.PushyBootReceiver" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<!-- Pushy Socket Service -->
<!-- Do not modify - internal service -->
<service android:name="me.pushy.sdk.services.PushySocketService" android:stopWithTask="false" />
<!-- Pushy Job Service (added in Pushy SDK 1.0.35) -->
<!-- Do not modify - internal service -->
<service android:name="me.pushy.sdk.services.PushyJobService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:stopWithTask="false" />
<!-- End Pushy Declarations -->
Configure ProGuard (Optional)
If your React Native project uses ProGuard, please make sure the following lines are present in your android/app/proguard-rules.pro
file:
-dontwarn me.pushy.**
-keep class me.pushy.** { *; }
-keep class androidx.core.app.** { *; }
-keep class android.support.v4.app.** { *; }
Modify App.tsx Component
Require the package in your App.tsx
file like so:
import Pushy from 'pushy-react-native';
Invoke Pushy.listen()
in your App.tsx
's App()
method to initialize the Pushy SDK:
function App(): React.JSX.Element {
// Start the Pushy service
Pushy.listen();
}
Register Devices
Users need to be uniquely identified to receive push notifications.
Every user is assigned a unique device token that you can use to push it at any given time. Once the user has been assigned a device token, it should be stored in your application's backend database.
Add the following code within a React.JSX.Element
method (i.e. App()
) to register the device for push notifications:
// Register the user for push notifications
Pushy.register()
.then(async deviceToken => {
// Display an alert with device token
alert('Pushy device token: ' + deviceToken);
// Print token to developer console
console.log('Pushy device token: ' + deviceToken);
// Send the token to your backend server via an HTTP GET request
//await fetch('https://your.api.hostname/register/device?token=' + deviceToken);
// Succeeded, optionally do something to alert the user
})
.catch(err => {
// Notify user of failure
alert('Registration failed: ' + err.message);
});
Listen for Notifications
Call the Pushy.setNotificationListener(data => {})
method in your App.tsx
file, right after the import
statements, outside any React.JSX.Element
method declarations:
// Place these lines of code right after the
// import statements in App.tsx as top-level code
Pushy.setNotificationListener(async data => {
// Print notification payload data
console.log('Received notification: ' + JSON.stringify(data));
// Notification title
let notificationTitle = 'MyApp';
// Attempt to extract the "message" property from the payload: {"message":"Hello World!"}
let notificationText = data.message || 'Test notification';
// Android: Displays a system notification
// iOS: Displays an alert dialog
Pushy.notify(notificationTitle, notificationText, data);
// Clear iOS badge count
Pushy.setBadge(0);
});
// Enable in-app notification banners (iOS 10+)
Pushy.toggleInAppBanner(true);
These methods must only be called from within your App.tsx
file, and should not be invoked from within a React.JSX.Element
method, or any other project file.
Note: Please make sure to add the android.permission.VIBRATE
permission declaration within your android/app/src/main/AndroidManifest.xml
if you'd like the notification to vibrate the device.
Feel free to modify this sample code to suit your own needs.
Listen for Notification Click
Call the Pushy.setNotificationClickListener(data => {})
method anywhere in your application to listen for when the user taps your notifications:
// Handle notification tap event
Pushy.setNotificationClickListener(async data => {
// Display basic alert
alert('Notification click: ' + data.message);
// Navigate the user to another page or
// execute other logic on notification click
});
Custom Notification Icon (Android)
Optionally configure a custom notification icon for incoming Android notifications by placing icon file(s) in android/app/src/main/res/drawable-*
and calling:
Pushy.setNotificationIcon('ic_notification');
Please invoke this method after Pushy.listen()
and replace ic_notification
with the resource file name, excluding the extension.
Note: If you don't call this method, or an invalid resource is provided, a generic icon will be used instead.
Parse Notification Data
Any payload data that you send with your push notifications is made available to your app via the data
parameter of your notification listener.
If you were to send a push notification with the following payload:
{"id": 1, "success": true, "message": "Hello World"}
Then you'd be able to retrieve each value from within your notification listener callback like so:
let id = data.id; // number
let success = data.success; // bool
let message = data.message; // string
Note: Unlike GCM / FCM, we do not stringify your payload data, except if you supply JSON objects or arrays.
Subscribe to Topics
Optionally subscribe the user to one or more topics to target multiple users with a shared interest when sending notifications.
Depending on your app's notification criteria, you may be able to leverage topics to simply the process of sending the same notification to multiple users. If your app only sends personalized notifications, skip this step and simply target individual users by their unique device tokens.
Add the following code within a React.JSX.Element
method (i.e. App()
) to subscribe the user to a topic:
// Make sure the user is registered
Pushy.isRegistered().then(isRegistered => {
if (isRegistered) {
// Subscribe the user to a topic
Pushy.subscribe('news').then(() => {
// Subscribe successful
alert('Subscribed to topic successfully');
}).catch(err => {
// Notify user of failure
alert('Subscribe failed: ' + err.message);
});
}
});
Note: Replace news
with your own case-sensitive topic name that matches the following regular expression: [a-zA-Z0-9-_.]+
.
You can then notify multiple users subscribed to a certain topic by specifying the topic name (prefixed with /topics/
) as the to
parameter in the Send Notifications API.
Send Test Notification
Input your device token and select your app to send a test push notification:
Note: You can specify a topic instead of a device token (i.e. /topics/news
). Also, if your app is not automatically detected, please manually copy the Secret API Key from the Dashboard and paste it into the form.
Did you receive the notification? If not, reach out, we'll be glad to help.
Congratulations on implementing Pushy in your React Native app!
To start sending push notifications to your users, start persisting device tokens in your backend, and invoke the Send Notifications API when you want to send a notification. Follow our step-by-step guide: