Push Notifications (Legacy)
Legacy Notice: This extension is already included as part of the core messaging experience and is scheduled for deprecation in the near future.
Please note: Legacy extensions are no longer actively maintained and will not receive feature updates or enhancements.
Learn how to send push notifications to mobile apps and desktop browsers.
Push notifications will work in iOS and Android apps as well as desktop browsers that support Push API. These browsers include:
- Chrome 50+
- Firefox 44+
- Edge 17+
- Opera 42+
Implementation
-
If you are new and want to implement Token-based Push Notifications in your app, follow our platform-specific guides:
-
JavaScript (Web)
- Android
- iOS
- Flutter
- React Native
-
For Android and iOS we also have setup that allows the usage of Native calling screens:
-
Token management to manage FCM and APNs tokens for the logged-in user.
-
Mute functionality to mute certain conversations or implement DND.
Web
The Push Notification extension allows you to send push notifications to mobile apps and desktop browsers.
Push notifications will work in all desktop browsers which support Push API. These include:
- Chrome 50+
- Firefox 44+
- Edge 17+
- Opera 42+
Firebase Project Setup
Visit Firebase Console and login/signup using your Gmail ID.
Step 1: Create a new Firebase Project
This is a simple 3 step process where:
- You give a name to your project
- Add Google Analytics to your project (Optional)
- Configure Google Analytics account (Optional)
Click on Create and you are ready to go.
Step 2: Add Firebase to your Web App
- Click on the Web icon on the below screen and Register your app with a nickname.
- Once done, click on Continue to Console.
Step 3: Download the service account file
Extension settings
Step 1: Enable the extension
- Login to CometChat and select your app.
- Go to the Extensions section and Enable the Push Notifications.
- Open the settings for the extension and add all the mentioned settings and hit save.
Step 2: Save your settings
On the Settings page you need to enter the following:
-
Set extension version
-
If you are setting it for the first time, Select
V2to start using the token-based version of the Push Notification extension. - If you already have an app using
V1and want to migrate your app to useV2, then SelectV1 & V2option. 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 offV1(Topic-based) Push Notifications completely. -
Select the platforms that you want to support
-
Select from Web, Android, Ionic (Deprecated), 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.
Web App Setup
Step 1: Folder and files setup
Create a folder with the following three files:
| Files | Description |
|---|---|
| index.html | Displays a simple User Login Form. |
| PushNotification.js | File with the logic to initialize CometChat and Firebase. |
| firebase-messaging-sw.js | Service worker shows Push Notifications when the tab is either in the background or closed. |
Step 2: Add the Firebase Config to the HTML File
- Go to the Firebase Console and click on the Web app and open up the Settings page.
- Go to the "General" tab on the Settings page.
- Scroll down and copy the Firebase SDK snippet and paste in the \ tag of your index.html file.
Step 3: Setup index.html file
-
Include the latest CometChat library using CDN.
-
Register the service worker file.
-
Also, include the
PushNotification.js. -
The \
has a simple form: -
Text input for UID.
- Login button.
- Logout button.
Once done, your index.html file should look like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Push Notification Sample</title>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.21.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.21.0/firebase-messaging.js"></script>
<!-- Firebase config and initialization -->
<script>
const FIREBASE_CONFIG = {
// Your Config
};
// Initialize Firebase only once
firebase.initializeApp(FIREBASE_CONFIG);
</script>
<!-- Register the service worker. -->
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/firebase-messaging-sw.js');
});
}
</script>
<!-- CometChat import -->
<script type="text/javascript" src="https://unpkg.com/@cometchat/chat-sdk-javascript/CometChat.js"></script>
<!-- Our app file with the CometChat and Firebase logic -->
<script src="PushNotification.js" defer></script>
</head>
<body>
Push Notifications (Legacy)</br>
<input type="text" id='uid'></input></br>
<button id='loginButton'>Login</button>
<button id='logoutButton'>Logout</button>
</body>
</html>
Step 4: Setup the service worker file
- Use
importScriptsto include thefirebase-app.jsandfirebase-messaging.jsfiles in the service worker. - Also paste in the
FIREBASE_CONFIGobject again in this file. - Initialize the Firebase object using the config.
- Call the messaging() on the Firebase object.
Once done, your firebase-messaging-sw.js file should look like this:
importScripts('https://www.gstatic.com/firebasejs/7.21.0/firebase-app.js');
importScripts(
'https://www.gstatic.com/firebasejs/7.21.0/firebase-messaging.js'
);
const FIREBASE_CONFIG = {
// Your Config
};
// Initialize firebase in the service worker.
firebase.initializeApp(FIREBASE_CONFIG);
// Start Receiving Push Notifications when
// the browser tab is in the background or closed.
firebase.messaging();
Step 5: Setup the PushNotification.js file
Now our simple web app has the following:
- Setup required to start using Firebase SDK.
- Service worker registration when the index.html loads for the first time.
Next, we can focus on the flow to setup CometChat login process along with the steps required to setup Push Notifications using Firebase Cloud Messaging (or FCM).
During login:
- Initialize CometChat.
- Login using CometChat user.
- Ask for the User's permission to show Push Notifications.
- If permission is granted, obtain the
FCM_TOKEN. - Register the obtained
FCM_TOKENwith the extension.
During logout:
- First delete the token using the firebase object.
- Logout CometChat user.
The above steps have been implemented in the login and logout functions in the PushNotifications.js file. You can copy paste the below code. Do not forget to replace the APP_ID, REGION, AUTH_KEY of your app in the code below.
const APP_ID = 'APP_ID';
const REGION = 'REGION';
const AUTH_KEY = 'AUTH_KEY';
const APP_SETTING = new CometChat.AppSettingsBuilder()
.subscribePresenceForAllUsers()
.setRegion(REGION)
.build();
let FCM_TOKEN = '';
let loginButton;
let logoutButton;
const login = async () => {
const UID = document.getElementById('uid').value;
if (!UID) {
document.getElementById('uid').focus();
return;
}
loginButton.disabled = true;
console.log('Initiating login... ');
try {
// CC init
await CometChat.init(APP_ID, APP_SETTING);
// User login
const loginResponse = await CometChat.login(UID, AUTH_KEY);
console.log('1. User login complete', loginResponse);
CometChat.getLoggedinUser().then((user) => console.log(user.name));
// Change the page title
document.title = UID + ' logged in';
// Fetch the FCM Token
const messaging = firebase.messaging();
FCM_TOKEN = await messaging.getToken();
console.log('2. Received FCM Token', FCM_TOKEN);
// Register the FCM Token
await CometChat.registerTokenForPushNotification(FCM_TOKEN);
console.log('3. Registered FCM Token');
logoutButton.disabled = false;
} catch (error) {
console.error(error);
}
};
const logout = async () => {
console.log('Initiating logout...');
loginButton.disabled = true;
logoutButton.disabled = true;
try {
// Delete the token
const messaging = firebase.messaging();
await messaging.deleteToken();
// Logout the user
await CometChat.logout();
console.log('5. Logged out');
// Refresh the page.
init();
window.location.reload();
} catch (error) {
console.error(error);
}
};
const init = () => {
// Basic initialization
loginButton = document.getElementById('loginButton');
logoutButton = document.getElementById('logoutButton');
loginButton.addEventListener('click', login);
logoutButton.addEventListener('click', logout);
logoutButton.disabled = true;
};
window.onload = () => {
// Call the initialization function on load.
setTimeout(init, 300);
};
Start receiving Push Notifications
- You can now host the project folder using Nginx, Apache web server, or even VSCode Live server extension.
- Launch the web app in a browser and open the browser console to see the logs.
- Enter the UID of the user and click on login.
- When asked for permission to show notifications, click on Allow.
- Once you see logs saying that the FCM Token has been registered, either send the browser tab to the background or close it completely.
- Send a message to this logged-in user from another device (using our Sample Apps) and you should be able to see the Push Notifications.
Stop receiving Push Notifications
- Reopen the previous closed browser tab and click on logout.
- The
FCM_TOKENwill be deleted on the extension's end on theCometChat.logout()call. - As a good practice, the
FCM_TOKENshould also be deleted using thefirebase.messaging().deleteToken().
Custom body for notifications
To send custom body for notifications or to receive notification of CustomMessage, you need to set metadata while sending the CustomMessage.
var receiverID = 'UID';
var customData = {
latitude: '50.6192171633316',
longitude: '-72.68182268750002',
};
var customType = 'location';
var receiverType = CometChat.RECEIVER_TYPE.USER;
var metadata = {
pushNotification: 'Your Notification Message',
};
var customMessage = new CometChat.CustomMessage(
receiverID,
receiverType,
customType,
customData
);
customMessage.setMetadata(metadata);
CometChat.sendCustomMessage(customMessage).then(
(message) => {
// Message sent successfully.
console.log('custom message sent successfully', message);
},
(error) => {
console.log('custom message sending failed with error', error);
// Handle exception.
}
);
Android
The Push Notification extension allows you to send push notifications to mobile apps and desktop browsers. In this section, we will see how to send Push Notifications to your Android app using Firebase Cloud Messaging or FCM.
Use Connection Service
If you want to use the System's native call service to handle calls, please refer to our guide on Android - Connection Service
Firebase Project Setup
Visit Firebase Console and login/signup using your Gmail ID.
Step 1: Create a new Firebase Project
On your Firebase Console, create a new project.
This is a simple 3 step process where:
- You give a name to your project
- Add Google Analytics to your project (Optional)
- Configure Google Analytics account (Optional)
Click on Create and you are ready to go.
Step 2: Add Firebase to your Android App
- Click on the Android icon as shown on the screen below.
-
Register your Android app by providing the following details:
-
Android Package name
- App nickname (optional)
- Debug signing certificate SHA-1 (optional)
- Download the
google-services.jsonfile and place it in the required location in your project.
- Add Firebase SDK by copying and pasting the snippets in the Project-level
build.gradlefile.
- Add Firebase SDK by copying and pasting the snippets in the App-level
build.gradlefile.
- Click on 'Continue to Console' to finish the setup.
Step 3: Download the service account file
Extension settings
Step 1: Enable the extension
- Login to CometChat and select your app.
- Go to the Extensions section and Enable the Push Notifications extension.
- Open the settings for this extension and save the following.
Step 2: Save your settings
On the Settings page you need to enter the following:
-
Set extension version
-
If you are setting it for the first time, Select
V2to start using the token-based version of the Push Notification extension. - If you already have an app using
V1and want to migrate your app to useV2, then SelectV1 & V2option. 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 offV1(Topic-based) Push Notifications completely. -
Select the platforms that you want to support
-
Select from Web, Android, Ionic (Deprecated), 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.
Android App Setup
In the Firebase Project setup, we did the following things:
- Added google-services.json file to the project.
- Added the required Firebase SDK snippets to the Project-level build.grade file.
- Added the required Firebase SDK snippets to the App-level build.gradle file.
If you want more details, check the Firebase Documentation.
Step 1: Register the FCM Token on user login
- Initialize CometChat and then login your user.
- On successful login, you can register the obtained FCM Token using
CometChat.registerTokenForPushNotification()function call. (You can see the process of getting the FCM Token in the next step)
CometChat.registerTokenForPushNotification(MyFirebaseMessagingService.token, new CometChat.CallbackListener() {
@Override
public void onSuccess(String s) {
Log.e( "onSuccessPN: ",s );
}
@Override
public void onError(CometChatException e) {
Log.e("onErrorPN: ",e.getMessage() );
}
});
CometChat.registerTokenForPushNotification(MyFirebaseMessagingService.token, object : CallbackListener
## Firebase Project Setup
Visit [Firebase Console](https://console.firebase.google.com/) and login/signup using your Gmail ID.
### Step 1: Create a new Firebase Project
On your Firebase Console, create a new project.
<div class="frame">
<img src="../images/06ec41e4-1623199646-7ba0cb45f033b090fc49ddb715b0cb2b.png" />
</div>
This is a simple 3 step process where:
1. You give a name to your project
2. Add Google Analytics to your project (Optional)
3. Configure Google Analytics account (Optional)
Click on Create and you are ready to go.
### Step 2: Add Firebase to your Android App
1. Click on the Android icon as shown on the screen below.
<div class="frame">
<img src="../images/a97e4e80-1623199648-2ae35edb70153eb724714719fc64c65d.png" />
</div>
2. Register your Android app by providing the following details:
1. Android Package name
2. App nickname (optional)
3. Debug signing certificate SHA-1 (optional)
<div class="frame">
<img src="../images/50ec55fb-1623199650-f637f75678b8c499486603de2346f1d3.png" />
</div>
3. Download the google-services.json file and place it in the required location in your project.
<div class="frame">
<img src="../images/9b3d3095-1623199651-d9506794806367499d7e2ce6fbf7ecbf.png" />
</div>
4. Add Firebase SDK by copying and pasting the snippets in the Project-level build.gradle file.
<div class="frame">
<img src="../images/e597c8dd-1623199652-e34b0f505c4af36ecd03d49dc0e4f564.png" />
</div>
5. Add Firebase SDK by copying and pasting the snippets in the App-level build.gradle file.
<div class="frame">
<img src="../images/d7a68604-1623199654-49dc03a0cc06cbdcab0573b82485c58c.png" />
</div>
6. Click on 'Continue to Console' to finish the setup.
### Step 3: Download the service account file
<div class="frame">
<img src="../images/2836ba6c-cometchat-firebase-get-service-account-3ed293fb42bfd421d5127639f2857277.png" />
</div>
## Extension settings
### Step 1: Enable the extension
1. Login to [CometChat](https://app.cometchat.com/login) and select your app.
2. Go to the Extensions section and Enable the Push Notifications extension.
3. Open the settings for this extension and save the following.
<div class="frame">
<img src="../images/790e609a-cometchat-extensions-push-notifications-2d0156e297965960863d547589c46044.png" />
</div>
### Step 2: Save your settings
On the Settings page you need to enter the following:
1. **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.
2. **Select the platforms that you want to support**
* Select from Web, Android, Ionic (Deprecated), React Native, Flutter & iOS.
3. **Notification payload settings**
* You can control if the notification key should be in the Payload or not. Learn more about the FCM Messages [here](https://firebase.google.com/docs/cloud-messaging).
4. **Push payload message options**
<div class="frame">
<img src="../images/10dbaaf4-cometchat-push-notifications-extension-settings-payload-message-options-28494a3c1ed3d9e7a65dd171d17cb12d.png" />
</div>
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.
5. **Notification Triggers**
<div class="frame">
<img src="../images/e53ecc4b-cometchat-extensions-push-notification-triggers-f847cdea801fcb44572e67c83d3faf66.png" />
</div>
* Select the triggers for sending Push Notifications. These triggers can be classified into 3 main categories:
1. Message Notifications
2. Call Notifications
3. Group Notifications
* These are pretty self-explanatory and you can toggle them as per your requirement.
## Android App Setup
In the Firebase Project setup, we did the following things:
1. Added google-services.json file to the project.
2. Added the required Firebase SDK snippets to the Project-level build.grade file.
3. Added the required Firebase SDK snippets to the App-level build.gradle file.
If you want more details, check the [Firebase Documentation](https://firebase.google.com/docs/cloud-messaging/android/client).
### Step 1: Register the FCM Token on user login
1. Initialize CometChat and then login your user.
2. On successful login, you can register the obtained FCM Token using `CometChat.registerTokenForPushNotification()` function call. (You can see the process of getting the FCM Token in the next step)
<div class="tabs-container"><div class="tabs-header"><button class="tab-button active" onclick="switchTab('tabs-12',0)">Java</button><button class="tab-button" onclick="switchTab('tabs-12',1)">Kotlin</button></div><div class="tab-panel active" data-tab-group="tabs-12" data-tab-index="0">
```java
CometChat.registerTokenForPushNotification(MyFirebaseMessagingService.token, new CometChat.CallbackListener() {
@Override
public void onSuccess(String s) {
Log.e( "onSuccessPN: ",s );
}
@Override
public void onError(CometChatException e) {
Log.e("onErrorPN: ",e.getMessage() );
}
});
CometChat.registerTokenForPushNotification(MyFirebaseMessagingService.token, object : CallbackListener
## Firebase Project Setup
Visit [Firebase Console](https://console.firebase.google.com/) and login/signup using your Gmail ID.
### Step 1: Create a new Firebase Project
On your Firebase Console, create a new project.
<div class="frame">
<img src="../images/73e8b456-1623199691-5b31d94dd3773f131401d7fad7ddde09.png" />
</div>
This is a simple 3 step process where:
1. You give a name to your project
2. Add Google Analytics to your project (Optional)
3. Configure Google Analytics account (Optional)
Click on Create and you are ready to go.
### Step 2: Add Firebase to your iOS App
1. Click on the iOS icon as shown on the screen below.
<div class="frame">
<img src="../images/b2742c90-1623199695-afe4a16ea5565a1fd775cf0714d51171.png" />
</div>
2. Register your Android app by providing the following details: a. iOS bundle name b. App nickname (optional) c. App Store ID (optional)
<div class="frame">
<img src="../images/a8d49795-PgAAAABJRU5ErkJggg.png" />
</div>
3. Download the GoogleService-Info.plist file and place it in the mentioned location of your project. Move your config file into the root of your Xcode project. If prompted, select to add the config file to all targets as follows.
<div class="frame">
<img src="../images/5c3dbf05-1623199698-11f789692d0519f2f0877d81ba759f49.png" />
</div>
<div class="frame">
<img src="../images/2e1fde5b-1623199699-d8679c0055666a6a84430c01acf1f91c.png" />
</div>
4. We will Add Firebase SDK and Initialisation code later. So, click on 'Next', 'Next', and 'Continue to the Console'.
### Step 3: Download the service account file
<div class="frame">
<img src="../images/2836ba6c-cometchat-firebase-get-service-account-3ed293fb42bfd421d5127639f2857277.png" />
</div>
## Extension settings
### Step 1: Enable the extension
1. Login to [CometChat](https://app.cometchat.com/login) and select your app.
2. Go to the Extensions section and Enable the Push Notifications extension.
3. Open the settings for this extension and save the following settings.
<div class="frame">
<img src="../images/790e609a-cometchat-extensions-push-notifications-2d0156e297965960863d547589c46044.png" />
</div>
### Step 2: Save your settings
On the Settings page you need to enter the following:
1. **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.
2. **Select the platforms that you want to support**
* Select from Web, Android, Ionic (Deprecated), React Native, Flutter & iOS.
3. **Notification payload settings**
* You can control if the notification key should be in the Payload or not. Learn more about the FCM Messages [here](https://firebase.google.com/docs/cloud-messaging).
4. **Push payload message options**
<div class="frame">
<img src="../images/10dbaaf4-cometchat-push-notifications-extension-settings-payload-message-options-28494a3c1ed3d9e7a65dd171d17cb12d.png" />
</div>
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.
5. **Notification Triggers**
<div class="frame">
<img src="../images/e53ecc4b-cometchat-extensions-push-notification-triggers-f847cdea801fcb44572e67c83d3faf66.png" />
</div>
* Select the triggers for sending Push Notifications. These triggers can be classified into 3 main categories:
1. Message Notifications
2. Call Notifications
3. Group Notifications
* These are pretty self-explanatory and you can toggle them as per your requirement.
## Get APNS Credentials
The following steps in this section are written on the assumption that you already have an app ID assigned to your client app.
### Step 1: Create a Certificate Signing Request
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.
1. Open the Keychain Access from the utility folder, go to Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority, and then click.
<div class="frame">
<img src="../images/6d8b61db-1623199712-167188509f2dcd817d2eb1714d3d1a01.png" />
</div>
2. 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.
<div class="frame">
<img src="../images/1838e7dc-1623199715-b21bded8a4ec5a159e9249376d0108a2.png" />
</div>
3. 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.
### Step 2: Create an SSL certificate
1. Sign in to your account at the [Apple Developer Member Center](https://developer.apple.com/membercenter).
2. Go to Certificates, Identifiers & Profiles. In the Identifiers > App IDs and select the Push Notifications service under Application Services
3. Click the Edit button.
<div class="frame">
<img src="../images/7125f94d-1623199719-a45e72df6870ea219ff5cc39700b69b1.png" />
</div>
4. Under the Push Notifications service, choose which SSL certificate to create either Development or Production.
<div class="frame">
<img src="../images/e376fc1b-1623199721-427d9042c79bfe2af928d0bbe44c8fb1.png" />
</div>
5. In the Generate your certificate pane that appears after the selection, under 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.
<div class="frame">
<img src="../images/af2efd86-1623199724-37f2d4286b1fcdf9acf4fafe5729d54c.png" />
</div>
6. In order to install the downloaded certificate to the KeyChain Access on your Mac, double-click it. You can find the certificate in the KeyChain Access > login > Certificates.
### Step 3: Export and update .p12 file to Firebase
1. Type a name for the .p12 file and save it to your Mac.
2. 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.
<div class="frame">
<img src="../images/f1dde893-1623199726-bf570172529d9b112076840694000c4d.png" />
</div>
### Step 4: Upload your APNs Certificates
1. Go to Firebase console and open your project.
2. Inside your iOS project in the Firebase console, select settings and then select the `Cloud Messaging` tab.
3. Scroll down to iOS app configuration, click the Upload button for APNS certificate.
4. Browse to the location where you saved your APNs Certificates, select it, and click Open.
<div class="frame">
<img src="../images/0d35bb99-1623199728-68f98b21a400a8e2f124b585329243d0.png" />
</div>
## iOS App Setup
### Step 1: Initial Firebase Cloud Messaging client setup
1. Add the Firebase SDK, Add the firebase pods that you want to install. You can include a Pod in your Podfile like this:
<div class="tabs-container"><div class="tabs-header"><button class="tab-button active" onclick="switchTab('tabs-17',0)">Swift</button></div><div class="tab-panel active" data-tab-group="tabs-17" data-tab-index="0">
```swift
pod 'Firebase_Core'
pod 'Firebase_Messaging'
- Import the Firebase module in your
ApplicationDelegate:
@import Firebase;
- Configure a FirebaseApp shared instance, typically in your application's
application:didFinishLaunchingWithOptions: method:
FirebaseApp.configure()
[FIRApp configure];
Step 2: Register the FCM Token
- Get the FCM Token for remote notifications, typically in your application's
application:didFinishLaunchingWithOptions: method:
Messaging.messaging().delegate = self
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {
_,
_ in
})
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
[FIRMessaging messaging].delegate = self;
if ([UNUserNotificationCenter class] != nil) {
[UNUserNotificationCenter currentNotificationCenter].delegate = self;
UNAuthorizationOptions authOptions = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions: authOptions completionHandler: ^ (BOOL granted, NSError * _Nullable error) {
// ...
}
];
} else {
UIUserNotificationType allNotificationTypes = (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
UIUserNotificationSettings * settings = [UIUserNotificationSettings settingsForTypes: allNotificationTypes categories: nil];
[application registerUserNotificationSettings: settings];
}
[application registerForRemoteNotifications];
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \\(error.localizedDescription)")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \\(deviceToken)")
Messaging.messaging().apnsToken = deviceToken
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(@"Unable to register for remote notifications: %@", error);
}
-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSLog(@"APNs device token retrieved: %@", deviceToken);
[FIRMessaging messaging].APNSToken = deviceToken;
}
- Register the FCM token with our Push Notifications extension on success of CometChat.login
let authKey = "XXXX XXXX XXXXX"
CometChat.login(UID: UID, authKey: authKey, onSuccess: { (user) in
DispatchQueue.main.async {
if let token = UserDefaults.standard.value(forKey: "fcmToken") as? String {
CometChat.registerTokenForPushNotification(token: token, onSuccess: { (success) in
print("onSuccess to registerTokenForPushNotification: \\(success)")
}) { (error) in
print("error to registerTokenForPushNotification")
}
}
- This also needs to be done when you refresh your FCM Token
extension AppDelegate : MessagingDelegate {
// [START refresh_token]
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \\(fcmToken)")
UserDefaults.standard.set(fcmToken, forKey: "fcmToken")
CometChat.registerTokenForPushNotification(token: fcmToken, onSuccess: { (sucess) in
print("token registered \\(sucess)")
}) { (error) in
print("token registered error \\(String(describing: error?.errorDescription))")
}
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
}
}
Step 3: Start receiving Push Notifications
- Receive remote notification, typically in your application's
App Delegate:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// Print full message.
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping(UIBackgroundFetchResult) -> Void) {
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// Print full message.
NSLog(@"%@", userInfo);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
// Print full message.
NSLog(@"%@", userInfo);
completionHandler(UIBackgroundFetchResultNewData);
}
- Receive Notification for
CustomMessage:
To receive and display push notifications for a CustomMessage, the developer must set metadata.pushNotification while sending the message. The value of this field is used as the notification text displayed to the recipient. If metadata.pushNotification is not set (or is null), the push notification will not be triggered for that message.
var receiverID = "cometchat-uid-1";
var message = [
"someRandomKey": "someRandomData"
];
var customMessage = CustomMessage(receiverUid: receiverID, receiverType: ReceiverTypeUser, customData: message);
// to display custom notification banner add this , "pushNotification" key is not to modify, although you can modify banner text as shown beow //
var customNotificationDisplayText = [
"pushNotification": "notification_banner_text_here";
];
// set it as metadata of `Custom message`
customMessage.metaData = customNotificationDisplayText;
CometChat.sendCustomMessage(withMessage: customMessage, onSuccess: { sentMessage in
print("sentMessage \\(sentMessage.stringValue)");
}, onError: { error in
if let error = error?.errorDescription() {
print("error sending custom message \\(error)");
}
});
NSString * receiverID = @ "cometchat-uid-1";
NSDictionary * message = [NSDictionary dictionaryWithObjectsAndKeys: @ "someRandomData", @ "someRandomKey", nil];
CustomMessage * customMessage = [
[CustomMessage alloc] initWithReceiverUid: receiverID receiverType: ReceiverTypeUser customData: message
];
// to display custom notification banner add this //
NSDictionary * customNotificationDisplayText = [NSDictionary dictionaryWithObjectsAndKeys: @ "notification_banner_text_here", @ "pushNotification", nil];
[customMessage setMetaData: customNotificationDisplayText];
[CometChat sendCustomMessageWithMessage: customMessage onSuccess: ^ (CustomMessage * _Nonnull sentMessage) {
NSLog(@ "sentMessage %@", [sentMessage stringValue]);
}
onError: ^ (CometChatException * _Nullable error) {
NSLog(@ "error sending custom message %@", [error errorDescription]);
}
];
Push Notification Payload sample for text and media messages-
{
"alert": "Nancy Grace: Text Message",
"sound": "default",
"title": "CometChat",
"message": {
"receiver": "cometchat-uid-4",
"data": {
"entities": {
"receiver": {
"entityType": "user",
"entity": {
"uid": "cometchat-uid-4",
"role": "default",
"name": "Susan Marie",
"avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp",
"status": "offline"
}
},
"sender": {
"entityType": "user",
"entity": {
"uid": "cometchat-uid-3",
"role": "default",
"name": "Nancy Grace",
"avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp",
"status": "offline"
}
}
},
"text": "Text Message"
},
"sender": "cometchat-uid-3",
"receiverType": "user",
"id": "142",
"sentAt": 1555668711,
"category": "message",
"type": "text"
}
}
{
"alert": "Nancy Grace: has sent an image",
"sound": "default",
"title": "CometChat",
"message": {
"receiver": "cometchat-uid-4",
"data": {
"attachments": [
{
"extension": "png",
"size": 14327,
"name": "extension_leftpanel.png",
"mimeType": "image/png",
"url": "https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
}
],
"entities": {
"receiver": {
"entityType": "user",
"entity": {
"uid": "cometchat-uid-4",
"role": "default",
"name": "Susan Marie",
"avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp",
"status": "offline"
}
},
"sender": {
"entityType": "user",
"entity": {
"uid": "cometchat-uid-3",
"role": "default",
"name": "Nancy Grace",
"avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp",
"status": "offline"
}
}
},
"url": "https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
},
"sender": "cometchat-uid-3",
"receiverType": "user",
"id": "145",
"sentAt": 1555671238,
"category": "message",
"type": "image"
}
}
Advanced
Convert Push Notification payload to Message object
CometChat SDK provides a method CometChat.CometChatHelper.processMessage() which will take the JSON received in The push notification as input, and return the corresponding TextMessage, MediaMessage,CustomMessage or Call object in return. Once the message object is received, you can use the entity as per your requirements.
This code needs to be added to the willPresent notification method of the UNUserNotificationCenterDelegate delegate.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if let userInfo = notification.request.content.userInfo as? [String : Any], let messageObject = userInfo["message"], let str = messageObject as? String, let dict = str.stringTodictionary() {
if let baseMessage = CometChat.processMessage(dict).0 {
switch baseMessage.messageCategory {
case .message:
if let message = baseMessage as? BaseMessage {
switch message.messageType {
case .text:
print("text Messagge is: \\((message as?TextMessage)?.stringValue())")
case .image:
print("image Messagge is: \\((message as? MediaMessage)?.stringValue())")
case .video:
print("video Messagge is: \\((message as? MediaMessage)?.stringValue())")
case .audio:
print("audio Messagge is: \\((message as? MediaMessage)?.stringValue())")
case .file:
print("file Messagge is: \\((message as? MediaMessage)?.stringValue())")
case .custom:
print("custom Messagge is: \\((message as? MediaMessage)?.stringValue())")
case .groupMember: break
@unknown default:break}
}
case .action: break
case .call:
if let call = baseMessage as? Call {
print("call is: \\(call.stringValue())")
}
case .custom:
if let customMessage = baseMessage as? CustomMessage {
print("customMessage is: \\(customMessage.stringValue())")
}
@unknown default: break
}
}
}
completionHandler([.alert, .badge, .sound])
}
extension String {
func stringTodictionary() -> [String:Any]? {
var dictonary:[String:Any]?
if let data = self.data(using: .utf8) {
do {
dictonary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
if let myDictionary = dictonary
{
return myDictionary;
}
} catch let error as NSError {
print(error)
}
}
return dictonary;
}
}
Miscellaneous
iOS APNs
Apple Push Notification service or APNs is used to send notifications to iOS devices. With this, you can also use Apple's CallKit for showing the call screen.
Get APNS Credentials
The following steps in this section are written on the assumption that you already have an app ID assigned to your client app.
Step 1: Create a Certificate Signing Request
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.
- 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.
Step 2: Create an SSL certificate
- Sign in to your account at the Apple Developer Member Center.
- Go to Certificates, Identifiers & Profiles.
- Create new Certificate by clicking on the + icon.
- 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.
Step 3: Export and update .p8 certificate
- To generate a .p8 key file, go to Apple Developer Account, then select Certificates, IDs & Profiles.
- 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 IDand yourBundle IDfor 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.
Extension settings
Step 1: Enable the extension
- Login to CometChat and select your app.
- Go to the Extensions section and Enable the Push Notifications extension.
- Open the settings for this extension and save the following.
Step 2: Save your settings
On the Settings page you need to enter the following:
-
Set extension version
-
The extension version has to be set to 'V2' or 'V1 & V2' in order to use APNs as the provider.
-
Select Platforms
-
You can select the platforms on which you wish to receive Push Notifications.
-
APNs Settings
-
You can turn off the Production mode when you create a development build of your application.
-
Upload the .p8 or .p12 certificate exported in the previous step.
-
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.
iOS App Setup
Initial Setup
- Call
CometChat.init()method to initialize CometChat in your application. This needs to be called only once. - The user has to be logged in using
CometChat.login()method. On the success callback, register the token with the extension. Two tokens need to be registered, out of which one is APNs token and other is CallKit token: a.CometChat.registerTokenForPushNotification(token: apnsToken, settings: ["voip":false])\
b.CometChat.registerTokenForPushNotification(token: voipToken, settings: ["voip":true])
let authKey = "XXXX XXXX XXXXX"
CometChat.login(UID: UID, authKey: authKey, onSuccess: { (current_user) in
DispatchQueue.main.async {
if let apnsToken = UserDefaults.standard.value(forKey: "apnsToken") as? String {
print("APNS token is: \(apnsToken)")
CometChat.registerTokenForPushNotification(token: apnsToken, settings: ["voip":false]) { (success) in
print("onSuccess to registerTokenForPushNotification: \(success)")
DispatchQueue.main.async {self.activityIndicator.stopAnimating()
print("login success with : \(current_user.stringValue())")
self.performSegue(withIdentifier: "presentPushNotification", sender: nil)
}
} onError: { (error) in
print("error to registerTokenForPushNotification")
}
}
if let voipToken = UserDefaults.standard.value(forKey: "voipToken") as? String {
print("VOIP token is: \(voipToken)")
CometChat.registerTokenForPushNotification(token: voipToken, settings: ["voip":true]) { (success) in
print("onSuccess to registerTokenForPushNotification: \(success)")
DispatchQueue.main.async {self.activityIndicator.stopAnimating()
print("login success with : \(current_user.stringValue())")
self.performSegue(withIdentifier: "presentPushNotification", sender: nil)
}
} onError: { (error) in
print("error to registerTokenForPushNotification")
}
}
}
}
}) { (error) in
print("error while login", error);
}
}
- Import PushKit and CallKit in AppDelegate.Swift file.
Receive Push Notifications
- Registering for the APNs notifications
var window: UIWindow?
var uuid: UUID?
var activeCall: Call?
var cancelCall: Bool = true
var onCall = true
var callController = CXCallController()
let voipRegistry = PKPushRegistry(queue: DispatchQueue.main)
var provider: CXProvider? = nil
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.voipRegistration()
// [START register_for_notifications]
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
// [END register_for_notifications]
return true
}
// Register for VoIP notifications
func voipRegistration() {
// Create a push registry object
let mainQueue = DispatchQueue.main
let voipRegistry: PKPushRegistry = PKPushRegistry(queue: mainQueue)
voipRegistry.delegate = self
voipRegistry.desiredPushTypes = [PKPushType.voIP]
}
- Add AppDelegate extension for receiving Push Notifications
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("willPresent notification: \(notification.request.content.userInfo)")
if let userInfo = notification.request.content.userInfo as? [String : Any], let messageObject =
userInfo["message"], let str = messageObject as? String, let dict = str.stringTodictionary() {
if let baseMessage = CometChat.processMessage(dict).0 {
switch baseMessage.messageCategory {
case .message:
if let message = baseMessage as? BaseMessage {
switch message.messageType {
case .text:
print("text Messagge is: \((message as? TextMessage)?.stringValue())")
case .image:
print("image Messagge is: \((message as? MediaMessage)?.stringValue())")
case .video:
print("video Messagge is: \((message as? MediaMessage)?.stringValue())")
case .audio:
print("audio Messagge is: \((message as? MediaMessage)?.stringValue())")
case .file:
print("file Messagge is: \((message as? MediaMessage)?.stringValue())")
case .custom:
print("custom Messagge is: \((message as? MediaMessage)?.stringValue())")
case .groupMember:
break
@unknown default:
break
}
}
case .action: break
case .call:
if let call = baseMessage as? Call {
print("call is: \(call.stringValue())")
}
case .custom:
if let customMessage = baseMessage as? CustomMessage {
print("customMessage is: \(customMessage.stringValue())")
}
@unknown default: break
}
}
}
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let notification = response.notification.request.content.userInfo
print("notification is 11: \(notification)")
completionHandler()
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("Device Token : ",token)
let hexString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
print("Device Token 11: ",hexString)
UserDefaults.standard.set(hexString, forKey: "apnsToken")
CometChat.registerTokenForPushNotification(token: hexString, settings: ["voip":false]) { (success) in
print("registerTokenForPushNotification voip: \(success)")
} onError: { (error) in
print("registerTokenForPushNotification error: \(error)")
}
}
}
- Add AppDelegate extension for VOIP notifications. Launch CallKit screen when the VOIP notification is received. Once the CallKit screen is displayed, you can Accept or Reject the CometChat call accordingly.
// MARK: CallKit & PushKit
extension AppDelegate: PKPushRegistryDelegate , CXProviderDelegate {
func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {
let deviceToken = pushCredentials.token.reduce("", {$0 + String(format: "%02X", $1) })
print("voip token is: \(deviceToken)")
UserDefaults.standard.set(deviceToken, forKey: "voipToken")
CometChat.registerTokenForPushNotification(token: deviceToken, settings: ["voip":true]) { (success) in
print("registerTokenForPushNotification voip: \(success)")
} onError: { (error) in
print("registerTokenForPushNotification error: \(error)")
}
}
func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: @escaping () -> Void) {
if let userInfo = payload.dictionaryPayload as? [String : Any], let messageObject =
userInfo["message"], let dict = messageObject as? [String : Any] {
if let baseMessage = CometChat.processMessage(dict).0 {
switch baseMessage.messageCategory {
case .message: break
case .action: break
case .call:
if let call = baseMessage as? Call {
switch call.callStatus {
case .initiated:
self.activeCall = call
self.uuid = UUID()
if let name = (call.sender)?.name {
let config = CXProviderConfiguration(localizedName: "APNS + Callkit")
config.iconTemplateImageData = #imageLiteral(resourceName: "your_app_icon").pngData()
config.includesCallsInRecents = false
config.ringtoneSound = "ringtone.caf"
config.supportsVideo = true
provider = CXProvider(configuration: config)
provider?.setDelegate(self, queue: nil)
let update = CXCallUpdate()
update.remoteHandle = CXHandle(type: .generic, value: name.capitalized)
if call.callType == .video {
update.hasVideo = true
}else{
update.hasVideo = false
}
provider?.reportNewIncomingCall(with: self.uuid!, update: update, completion: { error in
if error == nil {
self.configureAudioSession()
}
})
}
case .ongoing, .unanswered, .rejected, .busy, .cancelled:
if self.activeCall != nil {
if self.cancelCall {
self.end(uuid: self.uuid!)
}
}
case .ended: break
@unknown default: break }
}
case .custom: break
@unknown default: break
}
}
}
}
internal func configureAudioSession() {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord, options: [.mixWithOthers, .allowBluetooth, .defaultToSpeaker])
try AVAudioSession.sharedInstance().setActive(true)
} catch let error as NSError {
print(error)
}
}
func providerDidReset(_ provider: CXProvider) {
if let uuid = self.uuid {
onCall = true
provider.reportCall(with: uuid, endedAt: Date(), reason: .unanswered)
}
}
func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
if let activeCall = activeCall {
startCall()
}
action.fulfill()
}
func provider(_ provider: CXProvider, perform action: CXEndCallAction) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "didRejectButtonPressed"), object: nil, userInfo: nil)
end(uuid: self.uuid!)
onCall = true
if let activeCall = activeCall {
CometChat.rejectCall(sessionID: activeCall.sessionID ?? "", status: .rejected, onSuccess: {(rejectedCall) in
DispatchQueue.main.async {
CometChatSnackBoard.display(message: "CALL_REJECTED".localized(), mode: .info, duration: .short)
}
}) { (error) in
DispatchQueue.main.async {
if let errorMessage = error?.errorDescription {
CometChatSnackBoard.display(message: "CALL_REJECTED".localized(), mode: .info, duration: .short)
}
}
}
provider.reportCall(with: self.uuid!, endedAt: Date(), reason: .remoteEnded)
}
action.fail()
}
func provider(_ provider: CXProvider, didDeactivate audioSession: AVAudioSession) {
print(#function)
}
func provider(_ provider: CXProvider, timedOutPerforming action: CXAction) {
action.fulfill()
print(#function)
}
func provider(_ provider: CXProvider, perform action: CXSetHeldCallAction) {
print(#function)
}
func provider(_ provider: CXProvider, perform action: CXSetMutedCallAction) {
print(#function)
}
func end(uuid: UUID) {
print("endUUID",uuid)
let endCallAction = CXEndCallAction(call: uuid)
let transaction = CXTransaction()
transaction.addAction(endCallAction)
requestTransaction(transaction, action: "")
}
func setHeld(uuid: UUID, onHold: Bool) {
print("setHeld",uuid)
let setHeldCallAction = CXSetHeldCallAction(call: uuid, onHold: onHold)
let transaction = CXTransaction()
transaction.addAction(setHeldCallAction)
requestTransaction(transaction, action: "")
}
internal func requestTransaction(_ transaction: CXTransaction, action: String = "") {
callController.request(transaction) { error in
if let error = error {
print("Error requesting transaction: \(error)")
} else {
print("Requested transaction successfully")
}
}
}
public func startCall(){
let activeCall = CometChatCall()
cancelCall = false
activeCall.modalPresentationStyle = .fullScreen
if let window = UIApplication.shared.windows.first , let rootViewController = window.rootViewController {
var currentController = rootViewController
while let presentedController = currentController.presentedViewController {
currentController = presentedController
}
currentController.present(activeCall, animated: true, completion: nil)
}
}
}
Miscellaneous
Create view controller for Calls
Create a viewController which will start the call when the user starts the call.
class CometChatCall: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if let call = appDelegate.activeCall {
if (call.callInitiator as? User)?.uid != CometChat.getLoggedInUser()?.uid {
CometChat.acceptCall(sessionID: call.sessionID ?? "") { acceptedCall in
DispatchQueue.main.async {
let callSettings = CallSettings.CallSettingsBuilder(callView: self.view, sessionId: acceptedCall?.sessionID ?? "").setMode(mode: .MODE_SINGLE).build()
CometChat.startCall(callSettings: callSettings) { userJoined in
appDelegate.onCall = true
} onUserLeft: { onUserLeft in
} onUserListUpdated: { onUserListUpdated in
} onAudioModesUpdated: { onAudioModesUpdated in
} onUserMuted: { onUserMuted in
} onCallSwitchedToVideo: { onCallSwitchedToVideo in
} onRecordingStarted: { onRecordingStarted in
} onRecordingStopped: { onRecordingStopped in
} onError: { error in
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
} onCallEnded: { ended in
DispatchQueue.main.async {
var str = ""
if let uuuid = appDelegate.uuid {
print("CometChatCalls", uuuid)
}
self.dismiss(animated: true, completion: nil)
self.dismiss(animated: true)
}
}
}
} onError: { error in
}
}else{
let callSettings = CallSettings.CallSettingsBuilder(callView: self.view, sessionId: call.sessionID ?? "").setMode(mode: .MODE_SINGLE).build()
CometChat.startCall(callSettings: callSettings) { userJoined in
} onUserLeft: { onUserLeft in
} onUserListUpdated: { onUserListUpdated in
} onAudioModesUpdated: { onAudioModesUpdated in
} onUserMuted: { onUserMuted in
} onCallSwitchedToVideo: { onCallSwitchedToVideo in
} onRecordingStarted: { onRecordingStarted in
} onRecordingStopped: { onRecordingStopped in
} onError: { error in
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
} onCallEnded: { ended in
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
}
}
}
}
}
}
Convert Push Notification payload to Message object
CometChat SDK provides a method CometChat.CometChatHelper.processMessage() which will take the JSON received in The push notification as input, and return the corresponding TextMessage, MediaMessage,CustomMessage or Call object in return. Once the message object is received, you can use the entity as per your requirements.
This code needs to be added to the willPresent notification method of the UNUserNotificationCenterDelegate delegate.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if let userInfo = notification.request.content.userInfo as? [String : Any], let messageObject = userInfo["message"], let str = messageObject as? String, let dict = str.stringTodictionary() {
if let baseMessage = CometChat.processMessage(dict).0 {
switch baseMessage.messageCategory {
case .message:
if let message = baseMessage as? BaseMessage {
switch message.messageType {
case .text:
print("text Messagge is: \((message as?TextMessage)?.stringValue())")
case .image:
print("image Messagge is: \((message as? MediaMessage)?.stringValue())")
case .video:
print("video Messagge is: \((message as? MediaMessage)?.stringValue())")
case .audio:
print("audio Messagge is: \((message as? MediaMessage)?.stringValue())")
case .file:
print("file Messagge is: \((message as? MediaMessage)?.stringValue())")
case .custom:
print("custom Messagge is: \((message as? MediaMessage)?.stringValue())")
case .groupMember: break
@unknown default:break}
}
case .action: break
case .call:
if let call = baseMessage as? Call {
print("call is: \(call.stringValue())")
}
case .custom:
if let customMessage = baseMessage as? CustomMessage {
print("customMessage is: \(customMessage.stringValue())")
}
@unknown default: break
}
}
}
completionHandler([.alert, .badge, .sound])
}
extension String {
func stringTodictionary() -> [String:Any]? {
var dictonary:[String:Any]?
if let data = self.data(using: .utf8) {
do {
dictonary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
if let myDictionary = dictonary
{
return myDictionary;
}
} catch let error as NSError {
print(error)
}
}
return dictonary;
}
}
Flutter
Learn how to implement Push notifications for the Flutter platform using FCM as well as APNs. This document guides you to set up Flutter push notifications as follows:
- Using FCM to implement push notifications for messaging on Android and iOS.
- Using APN to implement push notifications for messaging on iOS.
Flutter Push notifications support
Push Notifications are supported in Flutter for CometChat SDK v3.0.9 and above.
FCM: Push notifications for messaging on Android and iOS
For Push notifications from FCM to work on both Android and iOS, the push payload has to be of type Notification message.
A Notification message is a push payload that has the notification key in it. These push notifications are handled directly by the OS and as a developer, you cannot customize these notifications.
This simple setup can be used for apps that only implement messaging feature of CometChat.
Learn more about FCM messages.
Step 1: Install packages
Add the following to your pubspec.yaml file under dependencies.
firebase_core: ^2.8.0
firebase_messaging: ^14.3.0
Install the packages.
flutter pub get
Step 2: Configure with flutterfire_cli
Use the following command to install flutterfire_cli
dart pub global activate flutterfire_cli
flutterfire configure --project=
This will ask you for the platforms. Select android and ios.
The CLI tool will add the following files to your directory structure:
google-services.jsonto the android folder.GoogleService-Info.plistto the ios folder.firebase_options.dartto thelibfolder.
In the build.gradle file, change:
// Change this:
classpath 'com.google.gms:google-services:4.3.10'
// to
classpath 'com.google.gms:google-services:4.3.14'
In your Firebase Console, go to project settings and upload the .p8 file obtained from the Apple Developer dashboard along with the Key ID and Team ID.
Step 3: FCM setup in app
This requires you to first set up a global context. It will help you in opening your app once your notification is tapped. Using this global context, you can write a function to navigate to the screen of choice once the notification is tapped.
class NavigationService {
static final GlobalKey navigatorKey =
GlobalKey();
static void navigateToChat(String text) {
navigatorKey.currentState?.push(
MaterialPageRoute(builder: (context) => ChatScreen(chatId: text)),
);
}
}
Once the user has logged in to CometChat, do the following to setup firebase:
-
Write a top-level function that is outside of any call. This function will handle the notifications when the app is not in the foreground.
-
Initialize firebase with the FirebaseOptions from the previous step.
-
Get an instance of firebase messaging
-
Request permissions
-
Set up listeners once the permission is granted:
-
Background notification listener
- Refreshed token listener that records the FCM token with the extension.
-
Notification tap listeners for background and terminated states of the app.
-
Make a call to save the FCM token with the extension.
Step 4: Setup for iOS
- Open the project in XCode (
ios/Runner.xcworkspace) - Add Push notifications capability.
- Add Background execution capability with Background fetch & Remote notification enabled.
- Inside the
iosfolder, executepod install.
Fore more details refer to the Firebase documentation.
Step 5: Run your application
Running the app in profile mode for iOS enables you to see the working once the app is terminated.
flutter run
flutter run --profile
Step 6: Extension setup (FCM)
- Login to CometChat dashboard.
- Go to the extensions section.
- Enable the Push notifications extension.
- Click on the settings icon to open the settings.
- Upload the service account file that is available on the Firebase Console.
- Make sure that you are including the
notificationkey in the payload. Otherwise, this won't work. - 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.
APN: Push notifications for messaging on iOS
Apple Push Notifications service or APNs is only available for Apple devices. This will not work on Android devices.
This setup ensures that the Push notifications for CometChat messages is sent using APNs device token.
Step 1: Install dependencies
Add the following to your pubspec.yaml file under dependencies.
flutter_apns_only: 1.6.0
Step 2: Add capabilities
- Open the project in XCode (
ios/Runner.xcworkspace) - Add Push notifications capability.
- Add Background modes capability with:
- Remote notifications
Step 3: Update AppDelegate.swift
Add the below to your AppDeletegate.swift file.
if #available(iOS 11.0, *) {
UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
Step 4: APN setup in app
Setup a global context to be able to open your app to a specific screen if the notification is tapped. Using the global context, write a function to navigate to the screen of your choice:
class NavigationService {
static final GlobalKey navigatorKey =
GlobalKey();
static void navigateToChat(String text) {
navigatorKey.currentState?.push(
MaterialPageRoute(builder: (context) => ChatScreen(chatId: text)),
);
}
}
Once the CometChat has been initialized and the user has logged in, do the required setup for the above packages that handle APNs and VoIP notifications.
Step 5: Run on a device
Run your app on a real device as Push notifications don't work on emulators.
Use the profile mode to see the behavior when the app is in the background or terminated states.
flutter run --profile
Step 6: Extension setup (APN)
- Login to CometChat dashboard.
- Go to the extensions section.
- Enable the Push notifications extension.
- Click on the settings icon to open the settings.
- Save the Team ID, Key ID, Bundle ID and upload the p8 certificate obtained from Apple Developer console.
- 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.
-
Save the settings.
React Native
Learn how to set up Push notifications for React Native using Firebase Cloud Messaging or FCM.
Firebase Project Setup
Visit Firebase and login/signup using your Gmail ID.
Step 1: Create a new Firebase Project
Head over to the Firebase Console to create a new project.
This is a simple 3 step process where:
- You give a name to your project
- Add Google Analytics to your project (Optional)
- Configure Google Analytics account (Optional)
Click on Create and you are ready to go.
Step 2: Add Firebase to your App
React native setup will require 2 files for Android and iOS:
- For Android, you need to download the google-services.json file from the Firebase console.
- For iOS, you need to download the GoogleService-Info.plist file from the Firebase console.
Step 3: Download the service account file
Extension settings
Step 1: Enable the extension
- Login to CometChat and select your app.
- Go to the Extensions section and Enable the Push Notifications extension.
- Open up the settings and save the following settings.
Step 2: Save your settings
On the Settings page you need to enter the following:
-
Set extension version
-
If you are setting it for the first time, Select
V2to start using the token-based version of the Push Notification extension. - If you already have an app using
V1and want to migrate your app to useV2, then SelectV1 & V2option. 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 offV1(Topic-based) Push Notifications completely. -
Select the platforms that you want to support
-
Select from Web, Android, Ionic (Deprecated), 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.
App Setup
Step 1: Initial plugin setup
- 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.
Step 2: Register FCM Token
- 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:
// Pseudo-code with async-await syntax
const 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:
// 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:
Step 3: Receive Notifications
// Pseudo-code
// Implementation can be done in a life-cycle method or hook
const 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
Step 4: Stop receiving Notifications
- Simply logout the CometChat user and you will stop receiving notifications.
- As a good practice, you can also delete the FCM Token by calling
deleteTokenon the messaging object.
// Pseudo-code using async-await syntax
logout = 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();
};
Advanced
Handle Custom Messages
To receive notification of CustomMessage, you need to set metadata while sending the CustomMessage.
var receiverID = 'UID';
var customData = {
latitude: '50.6192171633316',
longitude: '-72.68182268750002',
};
var customType = 'location';
var receiverType = CometChat.RECEIVER_TYPE.USER;
var metadata = {
pushNotification: 'Your Notification Message',
};
var customMessage = new CometChat.CustomMessage(
receiverID,
receiverType,
customType,
customData
);
customMessage.setMetadata(metadata);
CometChat.sendCustomMessage(customMessage).then(
(message) => {
// Message sent successfully.
console.log('custom message sent successfully', message);
},
(error) => {
console.log('custom message sending failed with error', error);
// Handle exception.
}
);
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.
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
{
"alert": "Nancy Grace: Text Message",
"sound": "default",
"title": "CometChat",
"message": {
"receiver": "cometchat-uid-4",
"data": {
"entities": {
"receiver": {
"entityType": "user",
"entity": {
"uid": "cometchat-uid-4",
"role": "default",
"name": "Susan Marie",
"avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp",
"status": "offline"
}
},
"sender": {
"entityType": "user",
"entity": {
"uid": "cometchat-uid-3",
"role": "default",
"name": "Nancy Grace",
"avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp",
"status": "offline"
}
}
},
"text": "Text Message"
},
"sender": "cometchat-uid-3",
"receiverType": "user",
"id": "142",
"sentAt": 1555668711,
"category": "message",
"type": "text"
}
}
{
"alert": "Nancy Grace: has sent an image",
"sound": "default",
"title": "CometChat",
"message": {
"receiver": "cometchat-uid-4",
"data": {
"attachments": [
{
"extension": "png",
"size": 14327,
"name": "extension_leftpanel.png",
"mimeType": "image/png",
"url": "https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
}
],
"entities": {
"receiver": {
"entityType": "user",
"entity": {
"uid": "cometchat-uid-4",
"role": "default",
"name": "Susan Marie",
"avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp",
"status": "offline"
}
},
"sender": {
"entityType": "user",
"entity": {
"uid": "cometchat-uid-3",
"role": "default",
"name": "Nancy Grace",
"avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp",
"status": "offline"
}
}
},
"url": "https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
},
"sender": "cometchat-uid-3",
"receiverType": "user",
"id": "145",
"sentAt": 1555671238,
"category": "message",
"type": "image"
}
}
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.
Setup push notification
- Android
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
Step 1: Create a Certificate Signing Request
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. \
\
\ - 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.
Step 2: Create an SSL certificate
- Sign in to your account at the Apple Developer Member Center.
- Go to Certificates, Identifiers & Profiles.
- Create new Certificate by clicking on the + icon.
- 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.
Step 3: Export and update .p8 certificate
- To generate a .p8 key file, go to Apple Developer Account, then select Certificates, IDs & Profiles.
- 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 IDand yourBundle IDfor 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.
Extension settings
Step 1: Enable the extension
- Login to CometChat and select your app.
- Go to the Extensions section and Enable the Push Notifications extension.
- Open the settings for this extension and save the following.
Step 2: Save your settings
On the Settings page you need to enter the following:
- Set extension version
The extension version has to be set to 'V2' or 'V1 & V2' in order to use APNs as the provider.
- Select Platforms
You can select the platforms on which you wish to receive Push Notifications.
- Firebase Cloud Messaging Settings
This includes the FCM Server key that you can fetch from the Firebase Dashboard.
- APNs Settings
You 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 Title
This is usually the name of your app.
- 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.
Installation
We need to add two packages for this
- React-native-CallKeep
This package also require some additional installation steps. Follow this link to install react-native-callkeep
npm install react-native-callkeep
//or
yarn add react-native-callkeep
- React Native VoIP Push Notification
This package also require some additional installation steps. Follow this link to install react-native-voip-push-notification.
npm install react-native-voip-push-notification
# --- if using pod
cd ios/ && pod install
App Setup
First you need to Setup CallKeep at the start of the app in Index.js
const options = {
ios: {
appName: 'My app name',
},
android: {
alertTitle: 'Permissions required',
alertDescription: 'This application needs to access your phone accounts',
cancelButton: 'Cancel',
okButton: 'ok',
imageName: 'phone_account_icon',
foregroundService: {
channelId: 'com.company.my',
channelName: 'Foreground service for my app',
notificationTitle: 'My app is running on background',
notificationIcon: 'Path to the resource icon of the notification',
},
},
};
RNCallKeep.setup(options);
RNCallKeep.setAvailable(true);
let callKeep = new CallKeepHelper();
In order to handle connectionService and CallKit we have made a helper call.
export default class CallKeepHelper {
constructor(msg) {
if (msg) {
CallKeepHelper.msg = msg;
}
this.setupEventListeners();
this.registerToken();
this.checkLoggedInUser();
this.addLoginListener();
CallKeepHelper.callEndedBySelf = false;
}
static FCMToken = null;
static voipToken = null;
static msg = null;
static callEndedBySelf = null;
static callerId = '';
static callerId1 = '';
static isLoggedIn = false;
checkLoggedInUser = async () => {
try {
let user = await CometChat.getLoggedinUser();
if (user) {
if (user) {
CallKeepHelper.isLoggedIn = true;
}
}
} catch (error) {
console.log('error checkLoggedInUser', error);
}
};
addLoginListener = () => {
var listenerID = 'UNIQUE_LISTENER_ID';
CometChat.addLoginListener(
listenerID,
new CometChat.LoginListener({
loginSuccess: (e) => {
CallKeepHelper.isLoggedIn = true;
this.registerTokenToCometChat();
},
})
);
};
registerTokenToCometChat = async () => {
if (!CallKeepHelper.isLoggedIn) {
return false;
}
try {
if (Platform.OS == 'android') {
if (CallKeepHelper.FCMToken) {
let response = await CometChat.registerTokenForPushNotification(
CallKeepHelper.FCMToken
);
}
} else {
if (CallKeepHelper.FCMToken) {
let response = await CometChat.registerTokenForPushNotification(
CallKeepHelper.FCMToken,
{ voip: false }
);
}
if (CallKeepHelper.voipToken) {
let response = await CometChat.registerTokenForPushNotification(
CallKeepHelper.voipToken,
{ voip: true }
);
}
}
} catch (error) {}
};
registerToken = async () => {
try {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
if (Platform.OS == 'android') {
let FCM = await messaging().getToken();
CallKeepHelper.FCMToken = FCM;
this.registerTokenToCometChat();
} else {
VoipPushNotification.registerVoipToken();
let FCM = await messaging().getAPNSToken();
CallKeepHelper.FCMToken = FCM;
this.registerTokenToCometChat();
}
}
} catch (error) {}
};
endCall = ({ callUUID }) => {
if (CallKeepHelper.callerId) RNCallKeep.endCall(CallKeepHelper.callerId);
_BackgroundTimer.start();
setTimeout(() => {
this.rejectCall();
}, 3000);
};
rejectCall = async () => {
if (
!CallKeepHelper.callEndedBySelf &&
CallKeepHelper.msg &&
CallKeepHelper.msg.call?.category !== 'custom'
) {
var sessionID = CallKeepHelper.msg.sessionId;
var status = CometChat.CALL_STATUS.REJECTED;
let call = await CometChat.rejectCall(sessionID, status);
_BackgroundTimer.stop();
} else {
_BackgroundTimer.stop();
}
};
static displayCallAndroid = () => {
this.IsRinging = true;
CallKeepHelper.callerId = CallKeepHelper.msg.conversationId;
RNCallKeep.displayIncomingCall(
CallKeepHelper.msg.conversationId,
CallKeepHelper.msg.sender.name,
CallKeepHelper.msg.sender.name,
'generic'
);
setTimeout(() => {
if (this.IsRinging) {
this.IsRinging = false;
RNCallKeep.reportEndCallWithUUID(CallKeepHelper.callerId, 6);
}
}, 15000);
};
// NOTE: YOU MIGHT HAVE TO MAKE SOME CHANGES OVER HERE AS YOU AS YOUR IMPLEMENTATION OF REACT-NATIVE-UI-KIT MIGHT BE DIFFERENT. YOU JUST NEED TO CALL THE ACCEPT CALL METHOD AND NAVIGATE TO CALL SCREEN.
answerCall = ({ callUUID }) => {
this.IsRinging = false;
CallKeepHelper.callEndedBySelf = true;
setTimeout(
() =>
navigate({
index: 0,
routes: [
{ name: 'Conversation', params: { call: CallKeepHelper.msg } },
],
}),
2000
);
// RNCallKeep.endAllCalls();
RNCallKeep.backToForeground();
if (Platform.OS == 'ios') {
if (AppState.currentState == 'active') {
RNCallKeep.endAllCalls();
_BackgroundTimer.stop();
} else {
this.addAppStateListener();
}
} else {
RNCallKeep.endAllCalls();
_BackgroundTimer.stop();
}
};
addAppStateListener = () => {
AppState.addEventListener('change', (newState) => {
if (newState == 'active') {
RNCallKeep.endAllCalls();
_BackgroundTimer.stop();
}
});
};
didDisplayIncomingCall = (DidDisplayIncomingCallArgs) => {
if (DidDisplayIncomingCallArgs.callUUID) {
if (Platform.OS == 'ios') {
CallKeepHelper.callerId = DidDisplayIncomingCallArgs.callUUID;
}
}
if (DidDisplayIncomingCallArgs.error) {
console.log({
message: `Callkeep didDisplayIncomingCall error: ${DidDisplayIncomingCallArgs.error}`,
});
}
this.IsRinging = true;
setTimeout(() => {
if (this.IsRinging) {
this.IsRinging = false;
// 6 = MissedCall
// https://github.com/react-native-webrtc/react-native-callkeep#constants
RNCallKeep.reportEndCallWithUUID(
DidDisplayIncomingCallArgs.callUUID,
6
);
}
}, 15000);
};
setupEventListeners() {
if (Platform.OS == 'ios') {
CometChat.addCallListener(
'this.callListenerId',
new CometChat.CallListener({
onIncomingCallCancelled: (call) => {
RNCallKeep.endAllCalls();
},
})
);
RNCallKeep.addEventListener('didLoadWithEvents', (event) => {
for (let i = 0; i < event.length; i++) {
if (event[i]?.name == 'RNCallKeepDidDisplayIncomingCall') {
CallKeepHelper.callerId = event[i]?.data?.callUUID;
}
}
});
VoipPushNotification.addEventListener('register', async (token) => {
CallKeepHelper.voipToken = token;
this.registerTokenToCometChat();
});
VoipPushNotification.addEventListener('notification', (notification) => {
let msg = CometChat.CometChatHelper.processMessage(
notification.message
);
CallKeepHelper.msg = msg;
});
VoipPushNotification.addEventListener(
'didLoadWithEvents',
async (events) => {
if (!events || !Array.isArray(events) || events.length < 1) {
return;
}
for (let voipPushEvent of events) {
let { name, data } = voipPushEvent;
if (
name ===
VoipPushNotification.RNVoipPushRemoteNotificationsRegisteredEvent
) {
CallKeepHelper.voipToken = data;
} else if (
name ===
VoipPushNotification.RNVoipPushRemoteNotificationReceivedEvent
) {
let msg = CometChat.CometChatHelper.processMessage(data.message);
CallKeepHelper.msg = msg;
}
}
}
);
}
RNCallKeep.addEventListener('endCall', this.endCall);
RNCallKeep.addEventListener('answerCall', this.answerCall);
}
removeEventListeners() {
RNCallKeep.removeEventListener('endCall');
RNCallKeep.removeEventListener('didDisplayIncomingCall');
RNCallKeep.removeEventListener('didLoadWithEvents');
VoipPushNotification.removeEventListener('didLoadWithEvents');
VoipPushNotification.removeEventListener('register');
VoipPushNotification.removeEventListener('notification');
}
}
Android
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.
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);
}
});
iOS
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
//add this import at the top or the file
#import "RNCallKeep.h"
#import "RNFBMessagingModule.h"
#import
## Firebase Project Setup
Visit [Firebase Console](https://console.firebase.google.com/) and login/signup using your Gmail ID.
### Step 1: Create a new Firebase Project
On your Firebase Console, create a new project.
<div class="frame">
<img src="../images/3d57f724-1623199661-12cb6d7fab6a98b2e70e66862265ab13.png" />
</div>
This is a simple 3 step process where:
1. You give a name to your project
2. Add Google Analytics to your project (Optional)
3. Configure Google Analytics account (Optional)
Click on Create and you are ready to go.
### Step 2: Add Firebase to your App
React native setup will require 2 files for Android and iOS:
1. For Android, you need to download the `google-services.json` file. You can refer to the [Android Firebase Project Setup - Step 2](#firebase-project-setup-2) and resume here once done.
2. For iOS, you need to download the `GoogleService-Info.plist` file. You can refer to the [iOS Firebase Project Setup - Step 2](#firebase-project-setup-4) and resume here once done.
3. For web, you need to have the Firebase Config object. You can refer to the [Web Firebase Project Setup - Step 2](#firebase-project-setup) and resume here once done.
### Step 3: Download the service account file
<div class="frame">
<img src="../images/2836ba6c-cometchat-firebase-get-service-account-3ed293fb42bfd421d5127639f2857277.png" />
</div>
## Extension settings
### Step 1: Enable the extension
1. Login to [CometChat](https://app.cometchat.com/login) and select your app.
2. Go to the Extensions section and Enable the Push Notifications extension.
3. Open the settings for this extension and save the following.
<div class="frame">
<img src="../images/790e609a-cometchat-extensions-push-notifications-2d0156e297965960863d547589c46044.png" />
</div>
### Step 2: Save your settings
On the Settings page you need to enter the following:
1. **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.
2. **Select the platforms that you want to support**
* Select from Web, Android, Ionic (Deprecated), React Native, Flutter & iOS.
3. **Notification payload settings**
* You can control if the notification key should be in the Payload or not. Learn more about the FCM Messages [here](https://firebase.google.com/docs/cloud-messaging/).
4. **Push payload message options**
<div class="frame">
<img src="../images/10dbaaf4-cometchat-push-notifications-extension-settings-payload-message-options-28494a3c1ed3d9e7a65dd171d17cb12d.png" />
</div>
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.
5. **Notification Triggers**
<div class="frame">
<img src="../images/e53ecc4b-cometchat-extensions-push-notification-triggers-f847cdea801fcb44572e67c83d3faf66.png" />
</div>
* Select the triggers for sending Push Notifications. These triggers can be classified into 3 main categories:
1. Message Notifications
2. Call Notifications
3. Group Notifications
* These are pretty self-explanatory and you can toggle them as per your requirement.
## App Setup
### Step 1: Initial plugin setup
1. For Cordova & Ionic, there are numerous plugins available via NPM which can be used to set up push notifications for your apps like [FCM Plugin](https://ionicframework.com/docs/v3/native/fcm/) and [Push Plugin](https://ionicframework.com/docs/native/push).
2. To setup Push Notification, you need to follow the steps mentioned in the Plugin's Documentation.
At this point, you will have:
1. Separate apps created on the Firebase console. (For Web, Android and iOS).
2. Plugin setup completed as per the respective documentation.
### Step 2: Register FCM Token
1. 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.
2. On the success callback of user login, you can fetch the FCM Token and register it with the extension as shown below:
<div class="tabs-container"><div class="tabs-header"><button class="tab-button active" onclick="switchTab('tabs-60',0)">JavaScript</button></div><div class="tab-panel active" data-tab-group="tabs-60" data-tab-index="0">
```js
// Pseudo-code with async-await syntax
// Using the FCM Plugin
const 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);
// Login is successful so next step
// Get the FCM device token
// You should have imported the following in the file:
// import { FCM } from '@ionic-native_fcm';
const FCM_TOKEN = await fcm.getToken();
// Register the token for 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:
// Pseudo-code
// You should have imported the following in the file:
// import { FCM } from '@ionic-native_fcm';
try {
// Listen to whether the token changes
return fcm.onTokenRefresh(FCM_TOKEN => {
await CometChat.registerTokenForPushNotification(FCM_TOKEN);
});
// ...
} catch(error) {
// Handle errors gracefully
}
For more details, visit documentation.
Step 3: Receive Notifications
// Pseudo-code
// Implementation can be done in a life-cycle method or hook
const unsubscribe = messaging().onMessage(async (remoteMessage) => {
Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
});
Step 4: Stop receiving Notifications
- On CometChat.logout will stop receiving notifications.
- As a good practice, you can also delete the FCM Token by calling
deleteTokenon the fcm object.
// Pseudo-code using async-await syntax
logout = async () => {
// User logs out of the app
await CometChat.logout();
};
Advanced
Handle Custom Messages
To receive notification of CustomMessage, you need to set metadata while sending the CustomMessage.
var receiverID = 'UID';
var customData = {
latitude: '50.6192171633316',
longitude: '-72.68182268750002',
};
var customType = 'location';
var receiverType = CometChat.RECEIVER_TYPE.USER;
var metadata = {
pushNotification: 'Your Notification Message',
};
var customMessage = new CometChat.CustomMessage(
receiverID,
receiverType,
customType,
customData
);
customMessage.setMetadata(metadata);
CometChat.sendCustomMessage(customMessage).then(
(message) => {
// Message sent successfully.
console.log('custom message sent successfully', message);
},
(error) => {
console.log('custom message sending failed with error', error);
// Handle exception.
}
);
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.
var processedMessage = CometChat.CometChatHelper.processMessage(JSON_MESSAGE);
Type of Attachment can be of the following the type:\
CometChatConstants.MESSAGE_TYPE_IMAGE\
CometChatConstants.MESSAGE_TYPE_VIDEO\
CometChatConstants.MESSAGE_TYPE_AUDIO\
CometChatConstants.MESSAGE_TYPE_FILE
Push Notification: Payload Sample for Text Message and Attachment/Media Message
{
"alert": "Nancy Grace: Text Message",
"sound": "default",
"title": "CometChat",
"message": {
"receiver": "cometchat-uid-4",
"data": {
"entities": {
"receiver": {
"entityType": "user",
"entity": {
"uid": "cometchat-uid-4",
"role": "default",
"name": "Susan Marie",
"avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp",
"status": "offline"
}
},
"sender": {
"entityType": "user",
"entity": {
"uid": "cometchat-uid-3",
"role": "default",
"name": "Nancy Grace",
"avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp",
"status": "offline"
}
}
},
"text": "Text Message"
},
"sender": "cometchat-uid-3",
"receiverType": "user",
"id": "142",
"sentAt": 1555668711,
"category": "message",
"type": "text"
}
}
{
"alert": "Nancy Grace: has sent an image",
"sound": "default",
"title": "CometChat",
"message": {
"receiver": "cometchat-uid-4",
"data": {
"attachments": [
{
"extension": "png",
"size": 14327,
"name": "extension_leftpanel.png",
"mimeType": "image/png",
"url": "https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
}
],
"entities": {
"receiver": {
"entityType": "user",
"entity": {
"uid": "cometchat-uid-4",
"role": "default",
"name": "Susan Marie",
"avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp",
"status": "offline"
}
},
"sender": {
"entityType": "user",
"entity": {
"uid": "cometchat-uid-3",
"role": "default",
"name": "Nancy Grace",
"avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp",
"status": "offline"
}
}
},
"url": "https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
},
"sender": "cometchat-uid-3",
"receiverType": "user",
"id": "145",
"sentAt": 1555671238,
"category": "message",
"type": "image"
}
}
Mute Functionality
Learn how to enable your users to mute notifications for certain conversations
You can silence one-on-one and/or group conversations for a specific amount of time using the Mute functionality. Aside from that, you can include a Push Notifications section in your apps' settings. Your users can use this feature to turn off Push Notifications for certain chats or to opt-out of receiving Push Notifications altogether.
Mute or Unmute Chats
Chat comprises anything related to messages like:
- New Message (Text, media, or Custom messages like Polls)
- Edited Message
- Deleted Message
- Response in threads
Mute Chats
You can specify the UIDs and/or GUIDs to be muted. You can mute chats for these conversations for a specific amount of time.
| Parameters | Value | Description |
|---|---|---|
| uids | Array of UIDs | This parameter allows you to mute one-on-one chat for the mentioned UIDs. |
| guids | Array of GUIDs | This parameter allows you to mute group chat for the mentioned GUIDs. |
| timeInMS | String consisting of UNIX timestamp | This parameter allows you to mute chats for a specific amount of time for the required UIDs or GUIDs After the mentioned duration, the Push Notifications are received. Eg: "1628425767881" |
This functionality uses the callExtension() method provided by CometChat SDK.
CometChat.callExtension('push-notification', 'POST', 'v2/mute-chat', {
"uids": ["cometchat-uid-1"],
"guids": ["cometchat-guid-1"],
"timeInMS": "1628610749081"
}).then(response => {
// Success
})
.catch(error => {
// Error occured
});
JSONObject body=new JSONObject();
JSONArray uids = new JSONArray();
JSONArray guids = new JSONArray();
uids.add("cometchat-uid-1");
guids.add("cometchat-guid-1");
body.put("uids", uids);
body.put("guids", guids);
body.put("timeInMS", "1628425767881");
CometChat.callExtension("push-notification", "POST", "/v2/mute-chat", body,
new CometChat.CallbackListener < JSONObject > () {
@Override
public void onSuccess(JSONObject jsonObject) {
//On Success
}
@Override
public void onError(CometChatException e) {
//On Failure
}
});
CometChat.callExtension(slug: "push-notification", type: .post, endPoint: "v2/mute-chat", body: ["uids":["cometchat-uid-1"], "guids":["cometchat-guid-1"], "timeInMS":"1628610749081"] as [String : Any], onSuccess: { (response) in
// Success
}) { (error) in
// Error occured
}
Unmute Chats
Used to unmute the chats for certain conversations before the mentioned time during muting.
| Parameters | Value | Description |
|---|---|---|
| uids | Array of UIDs | This parameter allows you to unmute one-on-one chat for the mentioned UIDs. |
| guids | Array of GUIDs | This parameter allows you to unmute group chat for the mentioned GUIDs. |
This functionality uses the callExtension() method provided by CometChat SDK.
CometChat.callExtension('push-notification', 'POST', 'v2/unmute-chat', {
"uids": ["cometchat-uid-1"],
"guids": ["cometchat-guid-1"]
}).then(response => {
// Success
})
.catch(error => {
// Error occured
});
JSONObject body=new JSONObject();
JSONArray uids = new JSONArray();
JSONArray guids = new JSONArray();
uids.add("cometchat-uid-1");
guids.add("cometchat-guid-1");
body.put("uids", uids);
body.put("guids", guids);
CometChat.callExtension("push-notification", "POST", "/v2/unmute-chat", body,
new CometChat.CallbackListener < JSONObject > () {
@Override
public void onSuccess(JSONObject jsonObject) {
//On Success
}
@Override
public void onError(CometChatException e) {
//On Failure
}
});
CometChat.callExtension(slug: "push-notification", type: .post, endPoint: "v2/unmute-chat", body: ["uids":["cometchat-uid-1"], "guids":["cometchat-guid-1"]] as [String : Any], onSuccess: { (response) in
// Success
}) { (error) in
// Error occured
}
Mute or Unmute Calls
You can mute the notifications for one-on-one or group calls. This works for Default calling (video or audio calls) offered by CometChat.
Mute Calls
You can specify the UIDs and/or GUIDs to be muted. You can mute calls for these conversations for the said amount of time.
| Parameters | Value | Description |
|---|---|---|
| uids | Array of UIDs | This parameter allows you to mute one-on-one calls for the mentioned UIDs. |
| guids | Array of GUIDs | This parameter allows you to mute group calls for the mentioned GUIDs. |
| timeinMS | String consisting of UNIX timestamp | This parameter allows you to mute calls for a specific amount of time for the required UIDs or GUIDs After the mentioned duration, the Push Notifications are received. Eg: "1628425767881" |
This functionality uses the callExtension() method provided by CometChat SDK.
CometChat.callExtension('push-notification', 'POST', 'v2/mute-calls', {
"uids": ["cometchat-uid-1"],
"guids": ["cometchat-guid-1"],
"timeInMS": "1628610749081"
}).then(response => {
// Success
})
.catch(error => {
// Error occured
});
JSONObject body=new JSONObject();
JSONArray uids = new JSONArray();
JSONArray guids = new JSONArray();
uids.add("cometchat-uid-1");
guids.add("cometchat-guid-1");
body.put("uids", uids);
body.put("guids", guids);
body.put("timeInMS", "1628425767881");
CometChat.callExtension("push-notification", "POST", "/v2/mute-calls", body,
new CometChat.CallbackListener < JSONObject > () {
@Override
public void onSuccess(JSONObject jsonObject) {
//On Success
}
@Override
public void onError(CometChatException e) {
//On Failure
}
});
CometChat.callExtension(slug: "push-notification", type: .post, endPoint: "v2/mute-calls", body: ["uids":["cometchat-uid-1"], "guids":["cometchat-guid-1"], "timeInMS":"1628610749081"] as [String : Any], onSuccess: { (response) in
// Success
}) { (error) in
// Error occured
}
Unmute Calls
Used to unmute calls for certain conversations before the mentioned time during muting.
| Parameters | Value | Description |
|---|---|---|
| uids | Array of UIDs | This parameter allows you to unmute one-on-one calls for the mentioned UIDs. |
| guids | Array of GUIDs | This parameter allows you to unmute group calls for the mentioned GUIDs. |
Used to unmute the calls for certain conversations before the mentioned time during muting.
CometChat.callExtension('push-notification', 'POST', 'v2/unmute-calls', {
"uids": ["cometchat-uid-1"],
"guids": ["cometchat-guid-1"]
}).then(response => {
// Success
})
.catch(error => {
// Error occured
});
JSONObject body=new JSONObject();
JSONArray uids = new JSONArray();
JSONArray guids = new JSONArray();
uids.add("cometchat-uid-1");
guids.add("cometchat-guid-1");
body.put("uids", uids);
body.put("guids", guids);
CometChat.callExtension("push-notification", "POST", "/v2/unmute-calls", body,
new CometChat.CallbackListener < JSONObject > () {
@Override
public void onSuccess(JSONObject jsonObject) {
//On Success
}
@Override
public void onError(CometChatException e) {
//On Failure
}
});
CometChat.callExtension(slug: "push-notification", type: .post, endPoint: "v2/unmute-calls", body: ["uids":["cometchat-uid-1"], "guids":["cometchat-guid-1"]] as [String : Any], onSuccess: { (response) in
// Success
}) { (error) in
// Error occured
}
User Settings
Apart from the feature to mute/unmute a set of UIDs or GUIDs using the above APIs, apps can have push notifications according to the user settings.
The following user settings can be set:
| Settings | Description |
|---|---|
| Do Not Disturb | When turned ON, the "Do Not Disturb" parameter disables the Push Notifications entirely for the user. The user stops receiving push notifications until this setting is explicitly turned OFF. This overrides all the following settings. |
| Allow only Mentions | Until turned OFF, the notifications are only sent for text messages for the mentioned receiver of the message |
| Mute all one-on-one chat | This parameter can be used to mute chat notifications for all one-on-one conversations. The user will not receive push notifications until this is turned OFF. |
| Mute all group chat | This parameter can be used to mute chat notifications for all group conversations. The user will not receive push notifications until the parameter is turned OFF. |
| Mute all one-on-one calls | This preference can be used to mute call notifications for all one-on-one conversations. The user will not receive push notifications until the parameter is turned OFF. |
| Mute all group calls | This parameter can be used to mute call notifications for all group conversations. The user will not receive push notifications until this is turned OFF. |
Save User Settings
The User settings object needs to be submitted as follows. All the fields are mandatory:
{
"user-settings": {
"dnd": "<boolean>",
"chat": {
"allow_only_mentions": "<boolean>",
"mute_group_actions": "<boolean>",
"mute_all_guids": "<boolean>",
"mute_all_uids": "<boolean>"
},
"call": {
"mute_all_guids": "<boolean>",
"mute_all_uids": "<boolean>"
}
}
}
This functionality uses the callExtension() method provided by CometChat SDK.
const userSettings = {
"user-settings": {
"dnd": false,
"chat": {
"allow_only_mentions": true,
"mute_group_actions": false,
"mute_all_guids": false,
"mute_all_uids": false
},
"call": {
"mute_all_guids": false,
"mute_all_uids":false
}
}
};
CometChat.callExtension('push-notification', 'POST', 'v2/user-settings', userSettings).then(response => {
// Success
})
.catch(error => {
// Error occured
});
JSONObject chatSettings = new JSONObject();
chatSettings.put('allow_only_mentions', false);
chatSettings.put('mute_group_actions', false);
chatSettings.put('mute_all_guids', false);
chatSettings.put('mute_all_uids', false);
JSONObject callSettings = new JSONObject();
callSettings.put('mute_all_guids', false);
callSettings.put('mute_all_uids', false);
JSONObject userSettings = new JSONObject();
userSettings.put('dnd', true);
userSettings.put('chat', chatSettings);
userSettings.put('call', callSettings);
CometChat.callExtension("push-notification", "GET", "/v2/user-settings", null,
new CometChat.CallbackListener < JSONObject > () {
@Override
public void onSuccess(JSONObject jsonObject) {
//On Success
}
@Override
public void onError(CometChatException e) {
//On Failure
}
});
CometChat.callExtension(slug: "push-notification", type: .get, endPoint: "v2/user-settings", body: {
"user-settings": {
"dnd": true_false,
"chat": {
"allow_only_mentions": true_false,
"mute_group_actions": true_false,
"mute_all_guids": true_false,
"mute_all_uids": true_false
},
"call": {
"mute_all_guids": true_false,
"mute_all_uids":true_false
}
}
}, onSuccess: { (response) in
// Success
}) { (error) in
// Error occured
}
Fetch User Settings
Fetches all the user settings that are saved by the user. This also returns the list of muted UIDs and GUIDs along with the said time for muting.
This functionality uses the callExtension() method provided by CometChat SDK.
CometChat.callExtension('push-notification', 'GET', 'v2/user-settings', null).then(response => {
// Success
})
.catch(error => {
// Error occured
});
CometChat.callExtension("push-notification", "GET", "/v2/user-settings", null,
new CometChat.CallbackListener < JSONObject > () {
@Override
public void onSuccess(JSONObject jsonObject) {
//On Success
}
@Override
public void onError(CometChatException e) {
//On Failure
}
});
CometChat.callExtension(slug: "push-notification", type: .get, endPoint: "v2/user-settings", body: nil, onSuccess: { (response) in
// Success
}) { (error) in
// Error occured
}
Token Management
Register tokens
Token registration can now be done using the callExtension method provided by the CometChat SDK. The token can be FCM token or APNs token and VoIP token.
This can be achieved using the code snippet below:
For FCM token:
// For FCM Token
CometChat.callExtension('push-notification', 'POST', 'v2/tokens', {
fcmToken: "fcm_token"
})
.then(response => {
// Success response
})
.catch(error => {
// Error occured
})
JSONObject body=new JSONObject();
body.put("fcmToken", "fcm_token");
CometChat.callExtension("push-notification", "POST", "/v2/tokens", body,
new CometChat.CallbackListener < JSONObject > () {
@Override
public void onSuccess(JSONObject jsonObject) {
//On Success
}
@Override
public void onError(CometChatException e) {
//On Failure
}
});
CometChat.callExtension(slug: "push-notification", type: .post, endPoint: "v2/tokens", body: ["fcmToken": "fcm_token"] as [String : Any], onSuccess: { (response) in
// success response
}) { (error) in
// Error occured
}
For APNs tokens:
// For APNs tokens
CometChat.callExtension('push-notification', 'POST', 'v2/tokens', {
apnsToken: "apns_token",
voipToken: "voip_token"
})
.then(response => {
// Success response
})
.catch(error => {
// Error occured
})
JSONObject body=new JSONObject();
body.put("apnsToken", "apns_token");
body.put("voipToken", "voip_token");
CometChat.callExtension("push-notification", "POST", "/v2/tokens", body,
new CometChat.CallbackListener < JSONObject > () {
@Override
public void onSuccess(JSONObject jsonObject) {
//On Success
}
@Override
public void onError(CometChatException e) {
//On Failure
}
});
CometChat.callExtension(slug: "push-notification", type: .post, endPoint: "v2/tokens", body: ["apnsToken": "apns_token", "voipToken": "voip_token"] as [String : Any], onSuccess: { (response) in
// Success response
}) { (error) in
// Error occured
}
Get tokens
This provides a list of all the Push Notifications tokens that have been registered for the current user. The tokens are segregated based on the platform.
CometChat.callExtension('push-notification', 'GET', 'v2/tokens', null)
.then(response => {
// Success response
})
.catch(error => {
// Error occured
})
CometChat.callExtension("push-notification", "GET", "/v2/tokens", null,
new CometChat.CallbackListener < JSONObject > () {
@Override
public void onSuccess(JSONObject jsonObject) {
//On Success
}
@Override
public void onError(CometChatException e) {
//On Failure
}
});
CometChat.callExtension(slug: "push-notification", type: .get, endPoint: "v2/tokens", body: nil, onSuccess: { (response) in
// Success response
}) { (error) in
// Error occured
}
The response will be as follows:
{
"ios": [
"cLztQGbuPA91bG3rkRcgcQYvlKuTlWGmHC1RnCwrTrbyT0VF"
],
"web": [
"cLztQGbuPA91bG3rkRcgcQYvlKuTlWGmHC1RnxyzTrbyT0VF"
],
"android": [
"dLztQGbuPA91bG3rkRckcQYvlKuTlWGmHC1RnxyzTrbyT0VF"
]
}
Delete tokens
Token deletion is handled implicitly by the CometChat.logout() method. That is, once the user is logged out of the current CometChat session, his/her registered Push Notification token automatically gets deleted.
The same can be achieved explicitly by making a call to the extension using callExtension method as shown below. However, the token that is deleted belongs to the current session of the end-user by passing all=false as a parameter.
CometChat.callExtension('push-notification', 'DELETE', 'v2/tokens', {
all: false, // true when ALL the registered tokens for the logged-in user need to be deleted
})
.then((response) => {
// Success response
})
.catch((error) => {
// Error occured
});
JSONObject body=new JSONObject();
body.put("all", false); // true when ALL the registered tokens for the logged-in user need to be deleted
CometChat.callExtension("push-notification", "DELETE", "/v2/tokens", body,
new CometChat.CallbackListener < JSONObject > () {
@Override
public void onSuccess(JSONObject jsonObject) {
//On Success
}
@Override
public void onError(CometChatException e) {
//On Failure
}
});
CometChat.callExtension(slug: "push-notification", type: .delete, endPoint: "v2/tokens", body: ["all": false] as [String : Any], onSuccess: { (response) in // true when ALL the registered tokens for the logged-in user need to be deleted
// Details about the created poll
}) { (error) in
// Error occured
}
All the tokens for the current user will be deleted if you pass all=true. This needs to be used with care as the other logins of the current user will stop receiving Push Notifications.