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
The SDK uses the Notifee library for push notifications. Prior to version 5.3.0, one was required to add a local maven repository in their android/build.gradle build script. For newer versions, this step is no longer necessary.
The core library for Notifee 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:
GROOVYallprojects {// ... you may have other items before the "repositories" section.repositories {// ... you will already have some local repositories defined ...// ADD THIS BLOCKmaven {url "$rootDir/../node_modules/@notifee/react-native/android/libs"}}}
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.
GROOVYapply plugin: 'com.android.application'// Add the following line:apply plugin: 'com.google.gms.google-services' // Google Services pluginandroid {// ...}
Finally, confirm that in your Project-level Gradle file ([YOUR_RN_PROJECT]/android/build.gradle
) you have
the Google services plugin as a buildscript dependency.
GROOVYbuildscript {repositories {// Make sure that you have the following two repositoriesgoogle() // Google's Maven repositorymavenCentral() // Maven Central repository}dependencies {...// Add the dependency for the Google services Gradle pluginclasspath 'com.google.gms:google-services:4.3.14'}}allprojects {...repositories {// Make sure that you have the following two repositoriesgoogle() // Google's Maven repositorymavenCentral() // Maven Central repository}}
Next, you can follow the Apple setup below or jump to registering push notification handlers.
To ensure your app properly handles push notifications, you need to enable two capabilities in your Xcode project:
Background Mode
capability - tickRemote Notifications
Push Notifications
capability
Follow this guide for how to add capabilities to your app on Xcode.
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.
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.
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".
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.
At the top of the file:
Objective-C#import <UserNotifications/UNUserNotificationCenter.h>
Then add the following line:
Objective-C@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate, UNUserNotificationCenterDelegate>
At the top of the file:
Objective-C#import <UserNotifications/UserNotifications.h>#import <RNCPushNotificationIOS.h>
Then, in the didFinishLaunchingWithOptions
method, add the highlighted lines below:
Objective-C- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{// Other code will be here// Define UNUserNotificationCenterUNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];center.delegate = self;return YES;}
Next, add the following lines below that method:
Objective-C// 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 *)userInfofetchCompletionHandler:(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.
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:
JavaScriptimport {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);
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<SessionappId='YOUR_APP_ID'me={{id: '123456789',name: 'Alice',photoUrl: 'https://talkjs.com/images/avatar-1.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.