CometChat Pro Documentation

You'll find comprehensive guides and documentation to help you start working with CometChat as quickly as possible. Let's jump right in!

IOS

This is a guide on how to enable push notification in your iOS App powered by CometChat Pro SDK. You can explore through the Demo Swift App OR Demo Objective-C App on Github.

Add Push Notification

  • To configure Firebase Push Notifications for your apps create a Firebase project at
    Firebase Console

Step 1: Add Firebase to your app

Create Firebase App

  • 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:

    • When prompted, enter your app's bundle identifier. It's important to enter the bundle identifier your app is using; this can only be set when you add the app to your Firebase project.
    • Click Download GoogleService-Info.plist to obtain your Firebase iOS config file

Download GoogleService-Info.plist

  • Move your config file into the root of your Xcode project. If prompted, select to add the config file to all targets as follows.

Add GoogleService-Info.plist to your project

Step 2: Upload your APNs Certificates

  • Configuring APNs with FCM.
  • Inside your project in the Firebase console, select the gear icon, select Project Settings, and then select the Cloud Messaging tab.
  • In APNs Certificates under iOS app configuration, click the Upload button.
  • Browse to the location where you saved your APNs Certificates, select it, and click Open. Add the key ID for the key (available in Certificates, Identifiers & Profiles in the Apple Developer Member Center) and click Upload.

Add APNS Certificate

Step 3: Add FCM Server Key

  1. Login to the CometChat Dashboard.
  2. On the Extensions page add the Push Notifications extension.
  3. Go to the Installed tab and open the Settings for this extension.
  4. Enter the Title (usually name of the app) and FCM Server key.
  5. You can also toggle the triggers for sending Push Notifications. The triggers can be classified into 3 main categories:
    a. Message Notifications
    b. Call Notifications
    c. Group Notifications

*Get your Firebase Cloud Messaging Server Key from Firebase Console as shown below:

FCM key at Firebase console

Step 4: Firebase Cloud Messaging client app on iOS

  • Add the Firebase SDK, Add the firebase pods that you want to install. You can include a Pod in your Podfile like this:
pod 'Firebase/Core'
pod 'Firebase/Messaging'
  • Import the Firebase module in your ApplicationDelegate:
import Firebase
@import Firebase;
  • Configure a FirebaseApp shared instance, typically in your application's application:didFinishLaunchingWithOptions: method:
FirebaseApp.configure()
[FIRApp configure];
  • Register for remote notification, 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];
  • The FCM registration token.
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;
}

Step 5: Subscribe to Topic

To receive notification from different entities, such as users and groups. The user has to subscribe to particular topics as We are using topic-based push notification. The topic will be generated as appId_receiverType_receiverId.

  • All client app will be subscribing to APPID_receiverType_ReceiverId_ios topic.

Subscribe to Type

Format

Example

User

APPID_ReceiverType_LoggedInUserUID_ios

6a124abc_user_SUPERHERO1_ios

Group

APPID_ReceiverType_GUID_ios

6a124abc_group_SUPERGROUP_ios

🚧

Please note:

UID in case of users and GUID in case of groups are converted to lowercase by the Chat API. These are then used for generating the topic.

let userTopic: String = appID + "_user_" + logged_in_user_UID + "_ios"

Messaging.messaging().subscribe(toTopic: userTopic) { error in
                print("Subscribed to \(userTopic) topic")
}
NSString *userTopic = [NSString allow] init];
userTopic = appID + "_user_" + logged_in_user_UID + "_ios";

[[FIRMessaging messaging] subscribeToTopic:@userTopic
                                completion:^(NSError * _Nullable error) {
  NSLog(@"Subscribed to userTopic topic %@",userTopic);
}];
let groupTopic: String = appID + "_group_" + group_guid + "_ios"

Messaging.messaging().subscribe(toTopic: groupTopic) { error in
                print("Subscribed to \(groupTopic) topic")
}
NSString *groupTopic = [NSString allow] init];
groupTopic = appID + "_group_" + group_guid + "_ios";

[[FIRMessaging messaging] subscribeToTopic:@groupTopic
                                completion:^(NSError * _Nullable error) {
  NSLog(@"Subscribed to userTopic topic %@",groupTopic);
}];
  • 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 notifications for CustomMessage, the developer needs to set metadata while sending the CustomMessage value as follows:

var receiverID = "SUPERHERO01";
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 = @ "SUPERHERO01";
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]);
  }
];
  • Dummy remote notification Payload:
{  
   "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"
   }
}

Step 6: Unsubscribe to Topic

To stop receiving notifications from different entities, such as users and groups. The user has to unsubscribe to particular topics, The topic will be generated as appId_receiverType_receiverId.

Unsubscribe from Type

Format

Example

User

APPID_ReceiverType_LoggedInUserUID_ios

6a124abc_user_SUPERHERO1_ios

Group

APPID_ReceiverType_GUID_ios

6a124abc_user_SUPERGROUP_ios

typically in your Logout method:

/**
* log out from `CometChatPro` and unsubscribe from `FCM` push notifications
*/
CometChat.logout(onSuccess: { (success) in

            Messaging.messaging().unsubscribe(fromTopic: userTopic)
            Messaging.messaging().unsubscribe(fromTopic: groupTopic)

}) {(error) in

}
/**
     * log out from `CometChatPro` and unsubscribe from `FCM` push notifications
     */
    [CometChat logoutOnSuccess:^(NSString * _Nonnull logoutSuccess) {
        
        [[FIRMessaging messaging] unsubscribeFromTopic:userTopic];
        [[FIRMessaging messaging] unsubscribeFromTopic:groupTopic];
        
    } onError:^(CometChatException * _Nonnull error) {
        
        NSLog(@"error in login %@",[error errorDescription]);
        
    }];

Converting push notification payload to message object

CometChat pro 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"]
           
          if let someString = messageObject as? String {
             
            if let dict = someString.stringTodictionary(){
               
             print("BaseMessage Object: \(CometChat.processMessage(dict))")
            }
         }
      }
}

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;
  }
}

Messages

Input

Notification Alert

Simple text message

SenderName: text message

Attachment(s) with text

SenderName: text message

An attachment without text

SenderName: has sent you a/an Type

Attachments without text

SenderName: has sent you Types

Apple Developer Portal

This section mainly describes how to obtain iOS and APNs credentials from the Apple Developer Portal and how to set up your iOS client app with the SDK to receive push notifications. 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 your 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 your push notification SSL certificate

  • Sign in to your account at the Apple Developer Member Center and choose Certificates, Identifiers & Profiles. In the Identifiers > App IDs, select the Push Notifications service under Application Services, and then 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.

Step 3: Export a .p12 file and upload to Firebase Dashboard

  • Type a name for the .p12 file and save it to your Mac.
  • Inside your project in the Firebase console, select the gear icon, select Project Settings, and then select the Cloud Messaging tab.
  • In APNs authentication key under iOS app configuration, click the Upload button.
  • 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 click Upload.

Increment App Icon Badge Count

Learn how to increment your app's icon badge count.


Launch chat window on tap of push notification

Learn how to launch a chat window from the UI Kit library on receiving a new message notification.


Launch call screen on tap of push notification

Learn how to launch an incoming call screen from the UI Kit library on receiving an incoming call notification.


Updated 9 days ago


IOS


This is a guide on how to enable push notification in your iOS App powered by CometChat Pro SDK. You can explore through the Demo Swift App OR Demo Objective-C App on Github.

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.