Migrate to Token-based Push NotificationsYou can check out our new Token-based implementation here.
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:
To configure Firebase Push Notifications for your apps create a Firebase project at Firebase Console.If you have previously not created a Firebase project for your app Click Add project. If you already have created a project for your app in which you wish to integrate CometChat, select the same project and download the config file.
In order to use the topic-based Push Notifications, you need to subscribe to topics. In case of CometChat, you need to subscribe to 2 different types of topics:
Topic to receive Push Notifications for one-on-one messages and calls.
Topic to receive Push Notifications for group messages and calls.
Also, you can:
Subscribe to one topic
Subscribe to all the topics
Below steps guide you with this process of subscription to topics and specific setup for the platform of your choice.
Before you logout the user using CometChat.logout() method, you can unsubscribe from topics to stop receiving Push notifications for a logged out user.
To enable Firebase products in your app, add the google-services plugin to your Gradle files.In your root-level (project-level) Gradle file (build.gradle), Check that you have Google’s Maven repository.In your module (app-level) Gradle file (usually app/build.gradle), apply the Google Services Gradle plugin and add the dependencies for the Firebase Cloud Messaging.
Report incorrect code
Copy
Ask AI
buildscript { repositories { // Check that you have the following line (if not, add it): google() // Google's Maven repository } dependencies { // ... // Add the following line: classpath 'com.google.gms:google-services:4.3.3' // Google Services plugin }}allprojects { // ... repositories { // Check that you have the following line (if not, add it): google() // Google's Maven repository // ... }}
CallNotificationAction.java is a Broadcast Receiver which is used to handle call events when app is in the background.Since Android O, there have been certain restrictions added for background tasks and users cannot launch intent directly from the service. More details can be found here.
Report incorrect code
Copy
Ask AI
package com.cometchat.pro.android.pushnotification.utils;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;import android.widget.Toast;import androidx.core.app.NotificationManagerCompat;import com.cometchat.pro.constants.CometChatConstants;import com.cometchat.pro.core.Call;import com.cometchat.pro.core.CometChat;import com.cometchat.pro.exceptions.CometChatException;import com.cometchat.pro.models.Group;import com.cometchat.pro.models.User;import constant.StringContract;import screen.CallActivity;public class CallNotificationAction extends BroadcastReceiver { String TAG = "CallNotificationAction"; @Override public void onReceive(Context context, Intent intent) { String sessionID = intent.getStringExtra(StringContract.IntentStrings.SESSION_ID); Log.e(TAG, "onReceive: " + intent.getStringExtra(StringContract.IntentStrings.SESSION_ID)); if (intent.getAction().equals("Answers")) { CometChat.acceptCall(sessionID, new CometChat.CallbackListener<Call>() { @Override public void onSuccess(Call call) { Intent acceptIntent = new Intent(context, CometChatCallActivity.class); acceptIntent.putExtra(StringContract.IntentStrings.SESSION_ID,call.getSessionId()); acceptIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(acceptIntent); } @Override public void onError(CometChatException e) { Toast.makeText(context,"Error "+e.getMessage(),Toast.LENGTH_LONG).show(); } }); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.cancel(05); } else { CometChat.rejectCall(sessionID, CometChatConstants.CALL_STATUS_REJECTED, new CometChat.CallbackListener<Call>() { @Override public void onSuccess(Call call) { NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context); notificationManager.cancel(05); } @Override public void onError(CometChatException e) { } }); } }}
You also need to add both of the above mentioned file in your AndroidManifest.xml to make Push notification work in Background as well.
6. Notification ChannelFrom Android O and above you need to use NotificationChannel to show notifications. You can add the below method in your Application class and call it in OnCreate(). This method will manage the notification channel for your app.
Report incorrect code
Copy
Ask AI
private void createNotificationChannel() { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is new and not in the support library if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.app_name); String description = getString(R.string.channel_description); int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel channel = new NotificationChannel("2", name, importance); channel.setDescription(description); channel.enableVibration(true); channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); // Register the channel with the system; you can't change the importance // or other notification behaviors after this NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); }}
The following steps in this section are written on the assumption that you already have an app ID assigned to your client app1. Create a Certificate Signing RequestTo 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.
Go to Certificates, Identifiers & Profiles. In the Identifiers > App IDs and select the Push Notifications service under Application Services
Click the Edit button.
Under the Push Notifications service, choose which SSL certificate to create either Development or Production.
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.
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.
3. Export and update .p12 file to Firebase
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.
4. Upload your APNs Certificates
Go to Firebase console and open your project.
Inside your iOS project in the Firebase console, select settings and then select the Cloud Messaging tab.
Scroll down to iOS app configuration, click the Upload button for APNS certificate.
Browse to the location where you saved your APNs Certificates, select it, and click Open.
The format for the name of user topic is AppID_user_UID_ios
The format for the name of a group topic is AppID_group_GUID_ios
Report incorrect code
Copy
Ask AI
let userTopic: String = appID + "_user_" + logged_in_user_UID + "_ios"Messaging.messaging().subscribe(toTopic: userTopic) { error in print("Subscribed to \\(userTopic) topic")}
Report incorrect code
Copy
Ask AI
/*** log out from `CometChat` and unsubscribe from `FCM` push notifications*/CometChat.logout(onSuccess: { (success) in Messaging.messaging().unsubscribe(fromTopic: userTopic) Messaging.messaging().unsubscribe(fromTopic: groupTopic)}) {(error) in}
3. Receive Remote notificationsThis typically happens in your application’s AppDelegate
Receive and display notifications for CustomMessage, you need to set the metadata while sending the CustomMessage:
Report incorrect code
Copy
Ask AI
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)"); }});
2. Android SetupTo allow the Android app to securely connect to your Firebase project, a configuration file must be downloaded and added to your project.Download the google-services.json file and place it inside of your project at the following location: /android/app/google-services.json.Configure Firebase in Android:To allow Firebase on Android to use the credentials, the google-services plugin must be enabled on the project. This requires modification to two files in the Android directory.Add the google-services plugin as a dependency inside of your /android/build.gradle.Execute the plugin by adding the following to your /android/app/build.gradle file.
Report incorrect code
Copy
Ask AI
buildscript { dependencies { // ... other dependencies classpath 'com.google.gms:google-services:4.3.3' // Add me --- _\\ }}
To allow the iOS app to securely connect to your Firebase project, a configuration file must be downloaded and added to your project.On the Firebase console, add a new iOS application and enter your project details. The “iOS bundle ID” must match your local project bundle ID. The bundle ID can be found within the “General” tab when opening the project with Xcode.Download the GoogleService-Info.plist file.Using Xcode, open the projects /ios/{projectName}.xcodeproj file (or /ios/{projectName}.xcworkspace if using Pods).Right-click on the project name and “Add files” to the project, as demonstrated below:
Select the downloaded GoogleService-Info.plist file from your computer, and ensure the “Copy items if needed” checkbox is enabled.
Configure Firebase in iOS:To allow Firebase on iOS to use the credentials, the Firebase iOS SDK must be configured during the bootstrap phase of your application.To do this, open your /ios/{projectName}/AppDelegate.m file, and add the following:At the top of the file, import the Firebase SDK:
Report incorrect code
Copy
Ask AI
#import <Firebase.h>
Within your existing didFinishLaunchingWithOptions method, add the following to the top of the method:
Report incorrect code
Copy
Ask AI
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Add me --- \\_ if ([FIRApp defaultApp] == nil) { [FIRApp configure]; } // Add me --- _\\ // ...}
In the Firebase console, you have to include either APNs Authentication Key or APNs Certificate in Project Settings > Cloud Messaging in order to receive push notifications.Turn on the following two capabilities in Xcode: a. Push Notifications & b. Background Modes - Check only Remote Notifications.
Lastly, Open your projects /ios/Podfile and add any of the globals shown below to the top of the file:
1. Firebase PluginsFor 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.To setup Push Notification, you need to follow the steps mentioned in the Plugin’s Documentation. You need to make different apps on the firebase console for each platform respectively (Android, iOS).2. Subscribe and unsubscribe processRefer to the JavaScript section above for subscription and unsubscription code.3. Receiving Push notificationsHere you can use the callback provided by the plugin. For eg: If you are using the FCM Plugin you can receive the messages as follows:
Report incorrect code
Copy
Ask AI
this.fcm.onNotification().subscribe((data) => { console.log("here you receive the message", data);});
This should ideally be added in the app.component.ts file and should be called in the success of the platform.ready().For other plugins, you can refer to the documentation provided by the plugin to check how messages can be received using that plugin. Once you have started receiving messages, you can act on the received messages accordingly as per your requirements.
CometChat SDK provides a method CometChat.CometChatHelper.processMessage() to convert the message JSON to the corresponding object of TextMessage, MediaMessage, CustomMessage, Action or Call.This code needs to be added to the onMessageReceived() method of the FirebaseMessagingService class.
Report incorrect code
Copy
Ask AI
let processedMessage = CometChat.CometChatHelper.processMessage(JSON_MESSAGE);
Attachments can be of the following types:CometChatConstants.MESSAGE_TYPE_IMAGE CometChatConstants.MESSAGE_TYPE_VIDEO CometChatConstants.MESSAGE_TYPE_AUDIO CometChatConstants.MESSAGE_TYPE_FILE