> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-013b37f0.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# iOS   FCM

Learn how to send out Push Notifications to your iOS using Firebase Cloud Messaging or FCM.

<Note>
  Don't want to use FCM?

  You can refer to [our setup](/notifications/ios-apns-push-notifications) using the Apple Push Notifications service (APNs).
</Note>

<Card title="I want to checkout the sample app" icon="github" href="https://github.com/cometchat/cometchat-push-notification-app-ios/tree/v4-push-notifications-extension">
  iOS Push notifications sample app

  View on Github
</Card>

## 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.

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/_ZVOct4_grytF_ZN/images/73e8b456-1623199691-5b31d94dd3773f131401d7fad7ddde09.png?fit=max&auto=format&n=_ZVOct4_grytF_ZN&q=85&s=8b1364b5184d8faa2a69f19e55b9e682" width="1673" height="698" data-path="images/73e8b456-1623199691-5b31d94dd3773f131401d7fad7ddde09.png" />
</Frame>

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.

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/vw_0NXjZvDpFf83K/images/b2742c90-1623199695-afe4a16ea5565a1fd775cf0714d51171.png?fit=max&auto=format&n=vw_0NXjZvDpFf83K&q=85&s=c516697216368521466c35117416a888" width="375" height="315" data-path="images/b2742c90-1623199695-afe4a16ea5565a1fd775cf0714d51171.png" />
</Frame>

2. Register your Android app by providing the following details: a. iOS bundle name b. App nickname (optional) c. App Store ID (optional)

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/ZhmN92ESUq6AiAGV/images/a8d49795-PgAAAABJRU5ErkJggg.png?fit=max&auto=format&n=ZhmN92ESUq6AiAGV&q=85&s=051cf764a9ffe57ae0a054ec14eefbd6" width="544" height="445" data-path="images/a8d49795-PgAAAABJRU5ErkJggg.png" />
</Frame>

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.

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/xkjVCc78V34-XITQ/images/5c3dbf05-1623199698-11f789692d0519f2f0877d81ba759f49.png?fit=max&auto=format&n=xkjVCc78V34-XITQ&q=85&s=a768357f7792795d263997223de74e71" width="733" height="491" data-path="images/5c3dbf05-1623199698-11f789692d0519f2f0877d81ba759f49.png" />
</Frame>

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/Y1jO_gcbgesM4HIm/images/2e1fde5b-1623199699-d8679c0055666a6a84430c01acf1f91c.png?fit=max&auto=format&n=Y1jO_gcbgesM4HIm&q=85&s=b6d7663b6f1a7bcfa4a213a29790a806" width="1679" height="477" data-path="images/2e1fde5b-1623199699-d8679c0055666a6a84430c01acf1f91c.png" />
</Frame>

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

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/Xl0-159t64EbEbQZ/images/2836ba6c-cometchat-firebase-get-service-account-3ed293fb42bfd421d5127639f2857277.png?fit=max&auto=format&n=Xl0-159t64EbEbQZ&q=85&s=96a5ab4487af6beb585d795917869c6e" width="3600" height="2400" data-path="images/2836ba6c-cometchat-firebase-get-service-account-3ed293fb42bfd421d5127639f2857277.png" />
</Frame>

## 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.

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/WpJt6WN_K73XvFJp/images/790e609a-cometchat-extensions-push-notifications-2d0156e297965960863d547589c46044.png?fit=max&auto=format&n=WpJt6WN_K73XvFJp&q=85&s=b1d1484570e5f5cd4e9285633b0c559c" width="1800" height="1200" data-path="images/790e609a-cometchat-extensions-push-notifications-2d0156e297965960863d547589c46044.png" />
</Frame>

### 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, 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/concept-options).

4. **Push payload message options**

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/3QMNZCcb2owfiSq_/images/10dbaaf4-cometchat-push-notifications-extension-settings-payload-message-options-28494a3c1ed3d9e7a65dd171d17cb12d.png?fit=max&auto=format&n=3QMNZCcb2owfiSq_&q=85&s=1007fd7a90b44f280fc47eb3f29f5e39" width="1800" height="1200" data-path="images/10dbaaf4-cometchat-push-notifications-extension-settings-payload-message-options-28494a3c1ed3d9e7a65dd171d17cb12d.png" />
</Frame>

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

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/Czw6a3oEz4RIW75k/images/e53ecc4b-cometchat-extensions-push-notification-triggers-f847cdea801fcb44572e67c83d3faf66.png?fit=max&auto=format&n=Czw6a3oEz4RIW75k&q=85&s=fee728f24569e2e046321364d66b0124" width="1800" height="1200" data-path="images/e53ecc4b-cometchat-extensions-push-notification-triggers-f847cdea801fcb44572e67c83d3faf66.png" />
</Frame>

* 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.

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/Z7OD8lxLTfsN-Ym-/images/6d8b61db-1623199712-167188509f2dcd817d2eb1714d3d1a01.png?fit=max&auto=format&n=Z7OD8lxLTfsN-Ym-&q=85&s=d2064a3c18318090e4c5a8a2744db62e" width="837" height="377" data-path="images/6d8b61db-1623199712-167188509f2dcd817d2eb1714d3d1a01.png" />
</Frame>

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.

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/IXQXQM27FFqKzSZd/images/1838e7dc-1623199715-b21bded8a4ec5a159e9249376d0108a2.png?fit=max&auto=format&n=IXQXQM27FFqKzSZd&q=85&s=a83e91feeac9dd95cda1196b8d7fabae" width="636" height="468" data-path="images/1838e7dc-1623199715-b21bded8a4ec5a159e9249376d0108a2.png" />
</Frame>

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.

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/_ZVOct4_grytF_ZN/images/7125f94d-1623199719-a45e72df6870ea219ff5cc39700b69b1.png?fit=max&auto=format&n=_ZVOct4_grytF_ZN&q=85&s=d392c88cc7771ffede897376516b518a" width="1664" height="715" data-path="images/7125f94d-1623199719-a45e72df6870ea219ff5cc39700b69b1.png" />
</Frame>

4. Under the Push Notifications service, choose which SSL certificate to create either Development or Production.

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/Czw6a3oEz4RIW75k/images/e376fc1b-1623199721-427d9042c79bfe2af928d0bbe44c8fb1.png?fit=max&auto=format&n=Czw6a3oEz4RIW75k&q=85&s=3070ad92278e136b41adcddb6f76c2b3" width="1658" height="795" data-path="images/e376fc1b-1623199721-427d9042c79bfe2af928d0bbe44c8fb1.png" />
</Frame>

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.

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/wmExTb2jx2mL9tyJ/images/af2efd86-1623199724-37f2d4286b1fcdf9acf4fafe5729d54c.png?fit=max&auto=format&n=wmExTb2jx2mL9tyJ&q=85&s=3eca57801262ecdd558dfe54eb222048" width="699" height="517" data-path="images/af2efd86-1623199724-37f2d4286b1fcdf9acf4fafe5729d54c.png" />
</Frame>

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.

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/QITwcxDdX4foDfQZ/images/f1dde893-1623199726-bf570172529d9b112076840694000c4d.png?fit=max&auto=format&n=QITwcxDdX4foDfQZ&q=85&s=f88fd9c99ffad713bbb900b5b37c319d" width="1669" height="410" data-path="images/f1dde893-1623199726-bf570172529d9b112076840694000c4d.png" />
</Frame>

### 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.

<Frame>
  <img src="https://mintcdn.com/cometchat-013b37f0/Ljt9AcZicJcNxpPO/images/0d35bb99-1623199728-68f98b21a400a8e2f124b585329243d0.png?fit=max&auto=format&n=Ljt9AcZicJcNxpPO&q=85&s=20592afc273d4539177920fe72a7bebe" width="746" height="503" data-path="images/0d35bb99-1623199728-68f98b21a400a8e2f124b585329243d0.png" />
</Frame>

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

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    pod 'Firebase_Core'
    pod 'Firebase_Messaging'
    ```
  </Tab>
</Tabs>

2. Import the Firebase module in your `ApplicationDelegate:`

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    import Firebase
    ```
  </Tab>

  <Tab title="Objective C">
    ```objc theme={null}
    @import Firebase;
    ```
  </Tab>
</Tabs>

3. Configure a FirebaseApp shared instance, typically in your application's `application:didFinishLaunchingWithOptions: method:`

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    FirebaseApp.configure()
    ```
  </Tab>

  <Tab title="Objective C">
    ```objc theme={null}
    [FIRApp configure];
    ```
  </Tab>
</Tabs>

### Step 2: Register the FCM Token

1. Get the FCM Token for remote notifications, typically in your application's `application:didFinishLaunchingWithOptions: method:`

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    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()
    ```
  </Tab>

  <Tab title="Objective C">
    ```objc theme={null}
    [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];
    ```
  </Tab>
</Tabs>

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    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
    }
    ```
  </Tab>

  <Tab title="Objective C">
    ```objc theme={null}
    -(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;
    }
    ```
  </Tab>
</Tabs>

2. Register the FCM token with our Push Notifications extension on success of CometChat.login

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    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")
         }
    }
    ```
  </Tab>
</Tabs>

3. This also needs to be done when you refresh your FCM Token

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    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)
        }
    }
    ```
  </Tab>
</Tabs>

### Step 3: Start receiving Push Notifications

1. Receive remote notification, typically in your application's `App Delegate:`

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    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)
    }
    ```
  </Tab>

  <Tab title="Objective C">
    ```objc theme={null}
    - (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);
    }
    ```
  </Tab>
</Tabs>

2. Receive Notification for `CustomMessage`:

To receive and display notifications for `CustomMessage`, the developer needs to set `metadata` while sending the `CustomMessage` value as follows:

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    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)");
        }
    });
    ```
  </Tab>

  <Tab title="Objective C">
    ```objc theme={null}
    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]);
      }
    ];
    ```
  </Tab>
</Tabs>

Push Notification Payload sample for text and media messages-

<Tabs>
  <Tab title="Text message">
    ```json theme={null}
    {
      "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"
      }
    }
    ```
  </Tab>

  <Tab title="Media message">
    ```json theme={null}
    {
      "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"
      }
    }
    ```
  </Tab>
</Tabs>

## 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.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    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;
      }
    }
    ```
  </Tab>
</Tabs>

### Miscellaneous

1. [Increment App Icon Badge Count](/sdk/ios/increment-app-icon-badge-count)
2. [Launch chat window on tap of push notification](/sdk/ios/launch-chat-window-on-tap-of-push-notification)
