On the Settings page you need to enter the following:
Set extension version
If you are setting it for the first time, Select V2 to start using the token-based version of the Push Notification extension.
If you already have an app using V1 and want to migrate your app to use V2, then Select V1 & V2 option. This ensures that the users viewing the older version of your app also receive Push Notifications.
Eventually, when all your users are on the latest version of your app, you can change this option to V2, thus turning off V1 (Topic-based) Push Notifications completely.
Select the platforms that you want to support
Select from Web, Android, Ionic, React Native, Flutter & iOS.
Notification payload settings
You can control if the notification key should be in the Payload or not. Learn more about the FCM Messages here.
Push payload message options
The maximum payload size supported by FCM and APNs for push notifications is approximately 4 KB. Due to the inclusion of CometChat’s message object, the payload size may exceed this limit, potentially leading to non-delivery of push notifications for certain messages. The options provided allow you to remove the sender’s metadata, receiver’s metadata, message metadata and trim the content of the text field.
The message metadata includes the outputs of the Thumbnail Generation, Image Moderation, and Smart Replies extensions. You may want to retain this metadata if you need to customize the notification displayed to the end user based on these outputs.
Notification Triggers
Select the triggers for sending Push Notifications. These triggers can be classified into 3 main categories:
Message Notifications
Call Notifications
Group Notifications
These are pretty self-explanatory and you can toggle them as per your requirement.
For React Native, there are numerous plugins available via NPM which can be used to set up push notifications for your apps. react-native-firebase and react-native-notifications are just the two out of many available.
To setup Push Notification, you need to follow the steps mentioned in the Plugin’s Documentation.
At this point, you will have:
Two separate apps created on the Firebase console. (For Android and iOS).
Plugin setup completed as per the respective documentation and our reference.
This step assumes that you already have a React Native app setup with CometChat installed. Make sure that the CometChat object is initialized and user has been logged in.
On the success callback of user login, you can fetch the FCM Token and register it with the extension as shown below:
Report incorrect code
Copy
Ask AI
// Pseudo-code with async-await syntaxconst APP_ID = 'APP_ID';const REGION = 'REGION';const AUTH_KEY = 'AUTH_KEY';const UID = 'UID';const APP_SETTINGS = new CometChat.AppSettingsBuilder() .subscribePresenceForAllUsers() .setRegion(REGION) .build();try { // First initialize the app await CometChat.init(APP_ID, APP_SETTINGS); // Login the user await CometChat.login(UID, AUTH_KEY); // Get the FCM device token // You should have imported the following in the file: // import messaging from '@react-native-firebase/messaging'; const FCM_TOKEN = await messaging().getToken(); // Register the token with Push Notifications (Legacy) await CometChat.registerTokenForPushNotification(FCM_TOKEN);} catch (error) { // Handle errors gracefully}
Registration also needs to happen in case of token refresh as shown below:
Report incorrect code
Copy
Ask AI
// Pseudo-code// You should have imported the following in the file:// import messaging from '@react-native-firebase/messaging';try { // Listen to whether the token changes return messaging().onTokenRefresh(FCM_TOKEN => { await CometChat.registerTokenForPushNotification(FCM_TOKEN); }); // ...} catch(error) { // Handle errors gracefully}
For React Native Firebase reference, visit the link below:
// Pseudo-codeimport messaging from '@react-native-firebase/messaging';import { Alert } from 'react-native';// Implementation can be done in a life-cycle method or hookconst unsubscribe = messaging().onMessage(async (remoteMessage) => { Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));});
We send Data Notifications and you need to handle displaying notifications at your end. For eg: Using Notifee
Simply logout the CometChat user and you will stop receiving notifications.
As a good practice, you can also delete the FCM Token by calling deleteToken on the messaging object.
Report incorrect code
Copy
Ask AI
// Pseudo-code using async-await syntaxlogout = async () => { // User logs out of the app await CometChat.logout(); // You should have imported the following in the file: // import messaging from '@react-native-firebase/messaging'; // This is a good practice. await messaging().deleteToken();};
Converting push notification payload to message object
CometChat SDK provides a method CometChat.CometChatHelper.processMessage() to convert the message JSON to the corresponding object of TextMessage, MediaMessage,CustomMessage, Action or Call.
Report incorrect code
Copy
Ask AI
var processedMessage = CometChat.CometChatHelper.processMessage(JSON_MESSAGE);
Type of Attachment can be of the following the type
1.CometChatConstants.MESSAGE_TYPE_IMAGE
2.CometChatConstants.MESSAGE_TYPE_VIDEO
3.CometChatConstants.MESSAGE_TYPE_AUDIO
4.CometChatConstants.MESSAGE_TYPE_FILE
Push Notification: Payload Sample for Text Message and Attachment/Media Message
Integrating ConnectionService and CallKit Using CometChat Push Notification
Currently we can only handle default calling notification
Whenever the user answers the call we use RNCallKeep.backToForeground(); method to bring the app in to foreground but in some devices you might need to add few more permissions for this to work For example, In MIUI 11 you need to permission for Display pop-up windows while running in the background
When the iOS app is in lock state we are not able to open the app so the call start on callkeep it self and you can hear the audio but if you want a video call then the user has to unlock the phone click on the app icon on call screen.
If you want to use the callkit and connection service in foreground then you might consider turning the callNotifications settings in UI kit settings. For more information in UI kit settings check the documentation.
Kindly follow the instruction for setting Firebase Cloud Messaging explained here
iOS
For iOS we use Apple Push Notification service or APNs to send push notification and VOIP notification. To configure this we need to follow some additional steps
To obtain a signing certificate required to sign apps for installation on iOS devices, you should first create a certificate signing request (CSR) file through Keychain Access on your Mac.
Open the Keychain Access from the utility folder, go to Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority, and then click.
The Certificate Information dialog box appears. Enter the email address that you use in your Apple Developer account, and enter a common name for your private key. Don’t enter CA email address, choose Saved to disk, and then click the Continue button. <img align=“center” src=”./images/step1.2.png”> <br></br>
Specify the name of your CSR to save and choose the location to save the file on your local disk. Then your CSR file is created, which contains a public/private key pair.
Under Services, select - Apple Push Notification services SSL (Sandbox & Production)
Select your App ID from the dropdown.
Upload CSR file., upload the CSR file you created through the Choose File button. To complete the process, choose Continue. When the certificate is ready, choose Download to save it to your Mac.
Select Keys and click on the ”+” button to add a new key.
In the new key page, type in your key name and check the Apple Push Notification service (APNs) box, then click “Continue” and click “Register”.
Then proceed to download the key file by clicking Download.
Make note of the Key ID, Team ID and your Bundle ID for saving in the Extension’s settings.
If you wish to use the .p12 certificate instead, do the following:
Type a name for the .p12 file and save it to your Mac.
Browse to the location where you saved your key, select it, and click Open. Add the key ID for the key (available in Certificates, Identifiers & Profiles in the Apple Developer Member Center) and export it.
DO NOT provide an export password when prompted.
The .p12 file will be required in the next step for uploading in the CometChat Dashboard.
On the Settings page you need to enter the following:
Set extension versionThe extension version has to be set to ‘V2’ or ‘V1 & V2’ in order to use APNs as the provider.
Select PlatformsYou can select the platforms on which you wish to receive Push Notifications.
Firebase Cloud Messaging SettingsThis includes the FCM Server key that you can fetch from the Firebase Dashboard.
APNs SettingsYou can turn off the Production mode when you create a development build of your application. Upload the .p12 certificate exported in the previous step.
Push Notifications TitleThis is usually the name of your app.
Notification TriggersSelect the triggers for sending Push Notifications. These triggers can be classified into 3 main categories:
Message Notifications
Call Notifications
Group Notifications
These are pretty self-explanatory and you can toggle them as per your requirement.
In android we are going to use Firebase push notification to display Call notification So basically when ever we receive a push notification for call we display call notification.we need to add a listener to listen to notification when the app is background or foreground state.
Report incorrect code
Copy
Ask AI
messaging().setBackgroundMessageHandler(async (remoteMessage) => { RNCallKeep.setup(options); RNCallKeep.setAvailable(true); try { //Converting the message payload into CometChat Message. let msg = CometChat.CometChatHelper.processMessage( JSON.parse(remoteMessage.data.message) ); if (msg.category == 'call') { //need to check if the notification we received for Call initiated or ended if (msg.action == 'initiated') { CallKeepHelper.msg = msg; //setting the msg object in call keep helper class CallKeepHelper.displayCallAndroid(); //this method is used to display incoming calls in android t } else { //if sender cancels the call before receiver accept or reject call then we also need to stop our notification RNCallKeep.endCall(msg.conversationId); } } } catch (e) { console.log(e); }});
In iOS we use APNs push and voip push notification to display push notification and display call CallKit for calls. The notification are handled in Native iOS You need to add the code in AppDelegate.m file to display CallKit
Report incorrect code
Copy
Ask AI
//add this import at the top or the file#import "RNCallKeep.h"#import "RNFBMessagingModule.h"#import <PushKit/PushKit.h>#import "RNVoipPushNotificationManager.h"_* <------ add this function *_- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(PKPushType)type { // Register VoIP push token (a property of PKPushCredentials) with server [RNVoipPushNotificationManager didUpdatePushCredentials:credentials forType:(NSString *)type];}- (void)pushRegistry:(PKPushRegistry *)registry didInvalidatePushTokenForType:(PKPushType)type{ // --- The system calls this method when a previously provided push token is no longer valid for use. No action is necessary on your part to re-register the push type. Instead, use this method to notify your server not to send push notifications using the matching push token.}// --- Handle incoming pushes- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type withCompletionHandler:(void (^)(void))completion { // --- NOTE: apple forced us to invoke callkit ASAP when we receive voip push // --- see: react-native-callkeep // --- Retrieve information from your voip push payload NSDictionary *content = [payload.dictionaryPayload valueForKey:@"aps"]; NSDictionary *sender = [content valueForKey:@"alert"]; NSString *uuid =[[[NSUUID UUID] UUIDString] lowercaseString]; NSString *callerName=[sender valueForKey:@"title"]; NSString *handle = [sender valueForKey:@"title"]; // --- Process the received push [RNVoipPushNotificationManager didReceiveIncomingPushWithPayload:payload forType:(NSString *)type]; [RNCallKeep reportNewIncomingCall: uuid handle: handle handleType: @"generic" hasVideo: NO localizedCallerName: callerName supportsHolding: YES supportsDTMF: YES supportsGrouping: YES supportsUngrouping: YES fromPushKit: YES payload: nil withCompletionHandler: completion];}