Ionic/Cordova

Learn how to setup CometChat Pro Enhanced Push notifications in Ionic/Cordova

The Push Notification extension allows you to send push notifications to mobile apps and desktop browsers.
In this section, we will see how to setup Push Notifications for Ionic/Cordova using Firebase Cloud Messaging or FCM.

I want to checkout the Sample app.

Click on the link below to check out our Ionic/Cordova Push Notifications Sample app.

Follow the steps mentioned in the README.md file.

View Sample App on GitHub

Firebase Project Setup

Visit Firebase Console 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.

Create Firebase AppCreate Firebase App

Create Firebase App

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 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 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 and resume here once done.

Step 3:

  1. Once you are back to Console, you will see the Web app added to the Firebase Project.
  2. Click on the app and open up the Settings page.
  3. Go to the "Cloud Messaging" section and get the Server Key. This will be required in the next step.

Extension Setup

Step 1: Enable the extension

  1. Login to the CometChat Dashboard.
  2. Select an existing app or create a new one.
  3. Go to the "Extensions" section and Enable the Push Notifications extension.
  4. Go to the "Installed" tab in the same section and open the settings for this extension.

Step 2: Save your Settings

On the Settings page you need to enter the following:

  1. Push Notifications Title
  • This is usually the name of your app.
  1. FCM Server key
  • Paste the Server key obtained in Step 3 of The Firebase Project Setup.
  1. Set extension version
  • If you are setting it for the first time, Select V2 to start using the enhanced version of the Push Notification extension. The enhanced version uses Token-based approach for sending Push Notifications and is simple to implement.
  • 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.
  1. 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

  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 and Push Plugin.

  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:
// 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 with Enhanced Push Notifications extension
  await CometChat.registerTokenForPushNotification(FCM_TOKEN);
} catch (error) {
  // Handle errors gracefully
}
  1. 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 FCM reference, visit the link below:

Step 3: Receive Notifications

// Pseudo-code
import messaging from '@react-native-firebase/messaging';
import { Alert } from 'react-native';

// 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

  1. On CometChat.logout will stop receiving notifications.
  2. As a good practice, you can also delete the FCM Token by calling deleteToken on 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 pro 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":"Spiderman: Text Message",
  "sound":"default",
  "title":"CometChat Pro",
  "message":{  
     "receiver":"superhero4",
     "data":{  
        "entities":{  
           "receiver":{  
              "entityType":"user",
              "entity":{  
                 "uid":"superhero4",
                 "role":"default",
                 "name":"Wolverine", 
                 "avatar":"http://data.cometchat.com/assets/images/avatars/wolverine.png",
                 "status":"offline"
              }
           },
           "sender":{  
              "entityType":"user",
              "entity":{  
                 "uid":"superhero3",
                 "role":"default",
                 "name":"Spiderman",
                 "avatar":"https://data.cometchat.com/assets/images/avatars/spiderman.png",
                 "status":"offline"
              }
           }
        },
        "text":"Text Message"
     },
     "sender":"superhero3",
     "receiverType":"user",
     "id":"142",
     "sentAt":1555668711,
     "category":"message",
     "type":"text"
  }
}
{
  "alert":"Spiderman: has sent an image",
  "sound":"default",
  "title":"CometChat Pro",
  "message":{
     "receiver":"superhero4",
     "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":"superhero4",
                 "role":"default",
                 "name":"Wolverine",
                 "avatar":"https://data.cometchat.com/assets/images/avatars/wolverine.png",
                 "status":"offline"
              }
           },
           "sender":{
              "entityType":"user",
              "entity":{
                 "uid":"superhero3",
                 "role":"default",
                 "name":"Spiderman",
                 "avatar":"https://data.cometchat.com/assets/images/avatars/spiderman.png",
                 "status":"offline"
              }
           }
        },
        "url":"https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
     },
     "sender":"superhero3",
     "receiverType":"user",
     "id":"145",
     "sentAt":1555671238,
     "category":"message",
     "type":"image"
  }
}

Mute functionality

Check out our documentation on how to add Mute functionality to your apps.


Did this page help you?