React Native Push Notifications

With our React Native SDK, we have made it easy to integrate TalkJS into your app. This guide will show you the necessary steps needed to setup and receive push notifications from TalkJS on React Native for both iOS and Android.

The guide assumes that you have setup the TalkJS React Native SDK as shown in our Getting Started guide

Android

Add local maven repository

The SDK used the Notifee library for push notifications. Its core library is packaged an Android "AAR" file which is distributed in a "local maven repository".

You must add this repository to your android/build.gradle build script file by adding these lines in your allprojects repositories section:

groovy
allprojects {
// ... you may have other items before the "repositories" section.
repositories {
// ... you will already have some local repositories defined ...
// ADD THIS BLOCK
maven {
url "$rootDir/../node_modules/@notifee/react-native/android/libs"
}
}
}

Add Firebase Messaging SDK to your project

If you haven't already, add Firebase to your project. Don't forget to add your FCM Server key in the TalkJS Dashboard.

Verify that you have the Firebase Android config file (google-services.json) in the directory: '[YOUR_RN_PROJECT]/android/app/'. Also, check that in your app-level Gradle file (usually app/build.gradle), you have applied the Google Services Gradle plugin.

groovy
apply plugin: 'com.android.application'
// Add the following line:
apply plugin: 'com.google.gms.google-services' // Google Services plugin
android {
// ...
}

Next, you can follow the Apple setup below or jump to registering push notification handlers.

iOS

Add Capabilities

To ensure your app properly handles push notifications, you need to enable two capabilities in your Xcode project:

  • Background Mode capability - tick Remote Notifications
  • Push Notifications capability

Follow this guide for how to add capabilities to your app on Xcode.

Generate Certification Request file (CSR)

You will use this file later when obtaining a push notification certificate from Apple. Open the Keychain Access app on your macOS system. Next, select Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority.... Enter your information in the required fields in the popup and select the Save to disk option. Save the file.

Obtain Push Notification certificate from Apple

In your Apple Developer Account, select Certificates, IDs & Profiles in the sidebar. Then go to, Identifiers. Locate and click the identifier that matches your app's BundleID on Xcode to edit it. If you don't have one, you can press the + (plus) button to create a new identifier. Under Capabilities make sure that Push Notifications is enabled.

Next, go to Certificates and create a new certificate by clicking the + (plus) button. Under Services, select Apple Push Notification service SSL (Sandbox & Production) and click Continue. The certificate will be applicable to both Sandbox and Production environments. Next, in the dropdown presented, choose the AppId (Your Team ID and Your app's Bundle ID separated by a fullstop) that has a BundleID that matches your App's. You will then be asked to upload a Certificate Signing Request. Use the file we created earlier using Keychain Access. Finally, click Download to save the certificate to your computer.

Upload Push Notification certificate

Double Click the Certificate you have just downloaded to add it to Keychain Access. In Keychain Access, select login under keychain and My Certificates from the side menu. Locate the Push Notifaction certificate and then right click it to export it.

In the window that appears, make sure the File Format is set to "Personal Information Exchange (.p12)". Click on "Save" to save it to your machine. When asked for a password, leave it blank and click on "Ok." Our TalkJS backend requires the Push Notification certificate to be a valid .p12 file without a password.

Now go to your TalkJS Dashboard and upload the .p12 file you have just exported. Once the upload is done, click on "Save Push Notification Settings".

Augment AppDelegate

You now need to add some code in your iOS app's AppDelegate.h and AppDelegate.m files. The code you will add will ensure the TalkJS SDK can properly register your device's token and process push notifications sent.

In AppDelegate.h

At the top of the file:

objectivec
#import <UserNotifications/UNUserNotificationCenter.h>

Then add the following line:

objectivec
@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, UNUserNotificationCenterDelegate>

In AppDelegate.m

At the top of the file:

objectivec
#import <UserNotifications/UserNotifications.h>
#import <RNCPushNotificationIOS.h>

Then, in the didFinishLaunchingWithOptions method, add the highlighted lines below:

objectivec
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Other code will be here
// Define UNUserNotificationCenter
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
return YES;
}

Next, add the following lines below that method:

objectivec
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
[RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}

That completes the iOS specific push notifications setup process.

Register Push Notification Handlers

Now, you will make a call to registerPushNotificationHandlers inside your app's index.js/index.tsx file. This function should not be called inside any component. This is because, when your application is killed either by the user swiping away from the recents screen or due to low memory on the device, any notifications received will not start the full app. This means that no component code will run and therefore no notifications will be displayed.

Aside from setting up the notification handlers, the function also creates an Android Notification Channel . Without a Notification Channel, notifications will not appear. (This applies only to Android devices)

Also, you can pass an object describing the different iOS permissions you'd like to be requested.

Below is an example index.js file:

javascript
import {AppRegistry} from 'react-native';
import {registerPushNotificationHandlers} from '@talkjs/react-native';
import App from './App';
import {name as appName} from './app.json';
registerPushNotificationHandlers(
{
channelId: 'com.example.reactnativetalkjs.messages',
channelName: 'My Messages',
},
{
sound: true,
badge: true,
alert: true,
}
);
AppRegistry.registerComponent(appName, () => App);

Enable push notifications

Finally, depending on whether your user actually wants to receive push notifications, you will use the prop, enablePushNotifications in the Session component to enable or disable push notifications being sent by the TalkJS backend to that particular device.

jsx
<Session
appId='YOUR_APP_ID'
me={{
id: '123456789',
name: 'Alice',
photoUrl: 'https://demo.talkjs.com/img/alice.jpg',
role: 'default'
}}
enablePushNotifications={true}
signature='HMAC-SHA256_OF_USER_ID'
/>

Now, users you have enablePushNotifications set to true will have message notifications displayed whenever the app is in the background.

If you have any issues receiving push notifications you can reach out to us via our support chat.