---
# System prepended metadata

title: Mobile Push Notifications

---

# Mobile Push Notifications

Push notifications help you communicate important information through mobile apps. It could be offers, app updates, important announcements, order information, or any other details that you want to notify your app users.

<center><img src="https://i.imgur.com/pYaY53f.jpg" width="50%"/></center>


You can send push notifications to Android or iOS applications using the following services:

* **Firebase Cloud Messaging** (FCM):  To send push notifications to Android apps.
* **Apple Push Notification Service** (APNS): To send push notifications to iOS apps.

## 1. Configure Android push notification

### Step 1: Add project to FCM & generate private key 

1. Log on to the [Firebase Developer Console](https://console.firebase.google.com/) and add Firebase to your [Android app](https://firebase.google.com/docs/android/setup).
![](https://i.imgur.com/wWLefrH.png)

2. In Project settings, navigate to **Service accounts**.

 ![](https://i.imgur.com/3Z1ga3w.png)

3. Click on **Generate new private key**. A JSON file will be downloaded which contains all the credentials.

   ![](https://i.imgur.com/Qzdl7Cf.png)


:::info

To set up Firebase Cloud Messaging client app on Android,  see the [Firebase official documentation](https://firebase.google.com/docs/cloud-messaging/android/client).
:::


### Step 2: Add key to Yellow.ai

Once you get the key JSON file, upload the key on Yellow.ai to establish a connection and grant access to send push notifications from Yellow.ai.

To connect FCM to yellow.ai, follow these steps:
1. Go to **Channels** > **Push Notifications** > **Android (FCM)**.
2. Click **Upload** and choose the downloaded JSON file.
3. Click **Add**.

![](https://secure-res.craft.do/v2/MXpitnt98nfq77xcERfHs5nKdeJUqQ42x1Paqh34KHvmo25ikVQryimMtxX8fAdU1SBcf9ZSL7SHduNiC1QsYBiwvFXXGgrEXzBXsR66jC14o7djEPtQKjWC2ZNyUmiYiYVsjd8UCUPNBKyRSKiXH3phdZF949jPshsBcT72G3ZqPoFiVGzQbgZLDEfUZSgDZZceh38sz116SVLCrGC4YFrLucpLLcUS41YppMQCXNEwcevcZYmjwagkzDJSJJvCPRUYTmqVkmC3r4sNaL511omqxMGaViz7HZw7LLyhEZVDifig8f/Image.jpg)

:::note
To know how to create a push notification campaign, see [Mobile push template](/docs/platform_concepts/engagement/outbound/templates/mobilepush.md).
:::

## 2. Code snippets for Android Push notifications

Notifications are sent to Firebase which then pushes them to the app using the user's device token. This section provides payloads that are sent to Firebase for different on-tap actions (action performed when the user taps on the push notification).

The following table provides descriptions of different parameters:

Parameter | Datatype | Description
--------- | -------- | ---------
notification | Object | Details of the notification
title | String | Title of the notification.
body | String | Content of the notification.
payload | String | Contains additional parameters such as image, botId, deeplink and journeySlug.
botId | String | The bot ID for which the notification has been triggered.
image | String | Path of the image file or URL of the image.
deeplink | String | URL which redirects the user to a particular page of the application.
journeySlug | String | The name of the journey which has to be triggered in the bot when the user taps on the notification
token | String | A unique identifier or device ID generated for the operating system and specific device. Notifications are sent to the user's device ID.

### 2.1 Notification without custom action
  
This is used for the On tap action, open the app (your app) - when a user clicks on the notification, it redirects to the main activity of the app.
We do not send any payload, instead, we just trigger the notification containing the title and body along with the image (if included). There is no action included in the payload.

```js
{
    "notification": {
        "title": "Hey there",
        "body": "Body",
        "image": "{ImageUrl}"
    },
    "token": "{deviceToken}"
}
```

### 2.2 Notification with deep link

This is used for the On tap action to open a deep link to the app - when a user clicks on the notification, it redirects to a specific screen of the app where the deeplink is pointing to.

The payload consists of the standard notification details (title, body, and image) along with the `botId` and `deeplink` URI.

```js
{
    "notification": {
        "title": "Hey there",
        "body": "Body",
        "image": "{imageUrl}"
    },
    "data": {
        "botId": {botId},
        "deeplink": "{uri}"
    },
    "token": "{deviceToken}"
}
```

### 2.3 Notification with bot response

This is used for the On tap action to open a specific bot flow - when a user clicks on the notification, it opens the bot that can trigger a specific bot flow or shows a predefined response.

#### Payload to trigger bot flow

Here is the payload to trigger a specific bot flow when the user clicks on the notification.

```js
{
    "notification": {
        "title": "Hey there",
        "body": "Body",
        "image": "{imageUrl}"
    },
    "data": {
        "botId": "{botId}",
        "journeySlug": "{slug}"
    },
    "token": "{deviceToken}"
}
```


#### Payload to open the bot with a predefined response

Here is the payload to show a specific bot response (text message) when the user clicks on the notification.

It just contains `botId` in the response under the `data` parameter. 

```js
{
    "notification": {
        "title": "Hey there",
        "body": "Body",
        "image": "{imageUrl}"
    },
    "data": {
        "botId": "{botId}",
    },
    "token": "{deviceToken}"
}
```
***

## 3. Implementation codes for Android app developer 

The following are the code snippets for the Android app developer to get the notifications and handle different scenarios.


### 3.1 Fetch additional data from notifications when clicked

Use the following code snippet to fetch additional information from the user when the user clicks on the notification.

```js
HashMap < String, Object > payloadData = new HashMap < > ();
HashMap < String, Object > botPayloadData = new HashMap < > ();

Bundle bundle = getIntent().getExtras();
if (bundle != null) {
    String tmp = "";
    for (String key: bundle.keySet()) {
        Object value = bundle.get(key);
        payloadData.put(key, value);
        tmp += key + ": " + value + "\n\n";
    }
    mTextView.setText(tmp);
}
```

### 3.3 Start chatbot with bot details additional data and bot details

Use the following code snippet to open the bot and trigger a specific bot flow when the user clicks on the notification. 

```js
if (payloadData.get("botId") != null) {
    String botId = (String) payloadData.get("botId");
    YMChat ymChat = YMChat.getInstance();

    ymChat.config = new YMConfig(botId);
    ymChat.config.version = 2;
    ymChat.config.ymAuthenticationToken = "2gs20emoof1666164936076";

    if (payloadData.get("journeySlug") != null) {
        String journeySlug = (String) payloadData.get("journeySlug");
        botPayloadData.put("JourneySlug", journeySlug);
        ymChat.config.payload = botPayloadData;
    }

    try {
        ymChat.startChatbot(this);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
```

### 3.1 Handle notifications in the foreground when the bot is closed

Use the following code snippet to handle the notifications you receive when the app is open in theforeground.

```js
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

class MyFirebaseMessagingService: FirebaseMessagingService() {
    final
    var TAG: String = "YMLog"
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        Log.i(TAG + " Remote message", remoteMessage.toString())
        Log.i(TAG + " Remote message", remoteMessage.data.toString())
        super.onMessageReceived(remoteMessage)
    }
}
```

:::info
For more details regarding the integration, see 
* [Android SDK documentation](https://docs.yellow.ai/docs/platform_concepts/mobile/chatbot/android). 
* [Test app with Android SDK and Firebase integration](https://github.com/yellowmessenger/YmChatBot-Android-DemoApp)
:::


***

## 1. Set up push notifications for iOS apps


To send push notifications on your iOS app using Yellow.ai, you must have an Apple Push Notification service (APNs) account configured with the app and upload the key file in Yellow.ai.

### Step 1: Create APNs private key

* Download the private key (.p8 file) with APNs enabled using these [instructions](https://developer.apple.com/help/account/).  Alternatively, you can also use an existing private key with APNs enabled.

### Step 2: Upload APNs private key on Yellow.ai

1. Go to **Channels** > **Push Notifications** > **iOS  (APNs)**.
2.  Click **Upload** and choose the .p8 file that you created.
3. Enter the *Key ID*, the Bundle ID and the Apple Team ID from the previous step.
4. Click **Add** to upload

![](https://secure-res.craft.do/v2/MXpitnt98nfq77xcERfHs5nKdeJUqQ42x1Paqh34KHvmo25ikVQryimMtxX8fAdU1SBcf9ZSL7SHduNiC1QsYBiwvFXXGgrEXzBXsR66jC14o7djEPtQKjWC2ZNyUmiYiYVsjd8UCUPNBKyRSKiXH3phczPr5qEBBoRoSV3iqCoFycXWFy15mVNCUZX1Adjze6y7ZKhWDgfpAD1441wesaaVVXcax81jmqN8N5cSPaSqPm19dLwQUjSGuofoMCvsVwi5P5tha29zHoQWcocWjaZXU4E41UbPy5C3aLWBEYofj9D5Wt/Image.jpg)


:::info
To know how to create a push notification campaign, see [Mobile push template](/docs/platform_concepts/engagement/outbound/templates/mobilepush.md).
:::

***
## 2. Code snippets for iOS Push notifications


Notifications are sent to Apple Push Notification Service (APNs) service which then pushes them to the app using the user's device. This section provides payloads that are sent to APN for different on-tap actions.

The following table provides descriptions of different parameters in the code snippets:


Parameter | Datatype | Description
------------ | ----- | -----------
title | String | Title of the notification.
body | String | Content of the notification.
payload | String | Additional parameters such as image, botId, deep-link and journeySlug.
botId | String | The bot ID for which the notification has been triggered.
image | String | The path to the image file or a URL of the image.
deeplink | String | URL which redirects the user to a particular page of the iOS application.
journeySlug | String | The name of the journey which has to be triggered in the bot, when the user taps on the notification.
contentAvailable | Boolean | Whether to handle background notifications.

### 2.1 Notification without custom action

This is used for the On tap action, open the app (your app) - when a user clicks on the notification, it redirects to the main activity of the app where the deeplink is pointing to.

We do not send any payload, instead, we just trigger the notification containing the title and body along with the image (if included). There is no action included in the payload.

```json
{
 "topic": {bundleId},
 "contentAvailable": true,
 "title": "hey there",
 "body": "description",
 "payload": {
 "image": "{imageUrl}"
 }
}
```


### 2.2 Notification with Deep-link

This is used for the On tap action to open a deep link to the app - when a user clicks on the notification, it redirects to a specific screen of the app.

The payload consists of the standard notification details (title, body, and image) along with the `botId` and `deeplink` URI.

```json
{
  "topic": "{bundleId}",
  "contentAvailable": true,
  "title": "hey there",
  "body": "description",
  "payload": {
    "image": "{imageUrl}",
    "botId": "{botID}",
    "deeplink": "{url}"
  }
}
```

### 2.3 Notification with bot response

This is used for the On tap action to open a specific bot flow - when a user clicks on the notification, it opens the bot that can trigger a specific bot flow or shows a predefined response.

#### Payload to trigger bot flow

Here is the payload to trigger a specific bot flow when the user clicks on the notification.

```json
{
  "topic": "{bundleId}",
  "contentAvailable": true,
  "title": "hey there",
  "body": "description",
  "payload": {
    "botId": "{botID}",
    "image": "{imageUrl}",
    "journeySlug": "slug"
  }
}
```

#### Payload to open the bot with a predefined response

Here is the payload to show a specific bot response (text message) when the user clicks on the notification.

It just contains `botId` in the response under the `data` parameter. 

```json
{
  "topic": "{bundleId}",
  "contentAvailable": true,
  "title": "hey there",
  "body": "description",
  "payload": {
    "botId": "{botID}",
    "image": "{imageUrl}",
  }
}
```
:::note
For code snippets on how to integrate the Yellow Messenger bot, see the following:
* [iOS chatbot](https://docs.yellow.ai/docs/platform_concepts/mobile/chatbot/ios)
* [YM chatbot iOS demo app](https://github.com/yellowmessenger/YMChatbot-iOS-DemoApp)
:::


## Implementation codes for iOS app developer

### Extract parameters from notifications

Use the following code snippet to define what happens when the user clicks on the notification. You can fetch additional data from the user when the user clicks on the notification.

```
class NotificationService: UNNotificationServiceExtension { 
  var contentHandler: ((UNNotificationContent) -> Void)? 
  var bestAttemptContent: UNMutableNotificationContent? 

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { 
self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

  let title = request.content.userInfo["title"]; 
  let body = request.content.userInfo["body"]; 
  let payload = request.content.userInfo["payload"]; 
  let botId = request.content.userInfo["payload"]["botId"]; 
  let image = request.content.userInfo["payload"]["image"]; 
  let journeySlug = request.content.userInfo["payload"]["journeySlug"]; 
  }
}
```

### 2 Handle image notifications

Use the following code snippet to handle image notifications.

```
import UserNotifications 
class NotificationService: UNNotificationServiceExtension { 
   var contentHandler: ((UNNotificationContent) -> Void)? 
   var bestAttemptContent: UNMutableNotificationContent? 

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { 
   self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) if let  
   bestAttemptContent = bestAttemptContent { // Modify the notification content here... bestAttemptContent.title = "\(bestAttemptContent.title) [modified]" 
   var urlString:String? = nil if let urlImageString = request.content.userInfo["image"] as? String { 
   urlString = urlImageString 
} 

if urlString != nil, let fileUrl = URL(string: urlString!) { print("fileUrl: \(fileUrl)") 

   guard let imageData = NSData(contentsOf: fileUrl) else { 
     contentHandler(bestAttemptContent) 
     return } 
   
   guard let attachment = UNNotificationAttachment.saveImageToDisk(fileIdentifier: "image.jpg", data: imageData, options: nil) else { 
   print("error in UNNotificationAttachment.saveImageToDisk()") 
   contentHandler(bestAttemptContent) 
   return 
 } 
   bestAttemptContent.attachments = [ attachment ] 
   } 
   contentHandler(bestAttemptContent) 
  } 
} 

override func serviceExtensionTimeWillExpire() { 
// Called just before the extension will be terminated by the system. 
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. 
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { 
   contentHandler(bestAttemptContent) 
   } 
  } 
} 

@available(iOSApplicationExtension 10.0, *) 
extension UNNotificationAttachment { 
static func saveImageToDisk(fileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? { 
  let fileManager = FileManager.default 
  let folderName = ProcessInfo.processInfo.globallyUniqueString 
  let folderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(folderName, isDirectory: true) do { 
  try fileManager.createDirectory(at: folderURL!, withIntermediateDirectories: true, attributes: nil) 
  let fileURL = folderURL?.appendingPathComponent(fileIdentifier) 
  try data.write(to: fileURL!, options: []) 
  let attachment = try UNNotificationAttachment(identifier: fileIdentifier, url: fileURL!, options: options) 
  return attachment 
} 
catch let error { 
  print("error \(error)") 
 } 
 return nil 
 } 
}
```

***

## Create Mobile push template


## Prerequisites

Before creating push notifications, you must have configured the following on the Yellow.ai platform.
- [Android push notification or Firebase Cloud Messaging channel](https://docs.yellow.ai/docs/platform_concepts/channelConfiguration/android_push) to send push notifications on the Android app
- [iOS or Apple Push Notifications](https://docs.yellow.ai/docs/platform_concepts/channelConfiguration/ios_push) to send push notifications on the iOS app



To create a Mobile push template, follow these steps:

1. Navigate to your project and go to **Engage** > **Templates**.
2. Click **+Create new templates** > **Mobile push notifications**.

<center>
<img src="https://i.imgur.com/s7tflBN.png" width=""/>
</center>

3. In **Template name**, enter a unique name for the template.
<center>
<img src="https://i.imgur.com/8thc54i.png" width="90%"/>
</center>

4. In **Message title**, enter the title of the notification.
5. In **Message**, enter the message content. Use `{{Name}}` to add variables in the content wherever required such as firstName, lastName, and city.
6. In **Image**, click **Upload** to add an image to the notification. It is recommended to use a 2:1 landscape image and the maximum size supported is 10 MB.
7. In **On tap action**, choose the action to be performed when the user taps on the push notification and click **Create template**. 

<center>
<img src="https://secure-res.craft.do/v2/MXpitnt98nfq77xcERfHs5nKdeJUqQ42x1Paqh34KHvmo25ikVQryimMtxX8fAdU1SBcf9ZSL7SHduNiC1QsYBiwvFXXGgrEXzBXsR66jC14o7djEPtQKjWC2ZNyUmiYiYVsjd8UCUPNBKyRSKiXH3phcsUxJQ6YNJq6GZgw1cwZ9wXTJceB63ByzUQEgAMTkcJFYfL2XjLrLqtD9NFNXvvEc5hL7YddsYtx54aiHEArxJGBma6vLfUtsrdJn2PkTGb9H5ms3HErmocZBYeYEtxXkfR7vH1XssMVsw9p7ZKiesGoKT/Image.jpg" width="70%"/>
</center>

The following are the possible actions when a user taps on the push notification:

#### Your app
Choose to redirect the user to the main activity of the app where the deeplink is pointing to.

#### A deep link to your app
Choose to redirect the recipient to a specific screen of the app.
   
   <img src="https://i.imgur.com/FF5lZUh.png" width="70%"/>

   - Enter the URI in the **Android deeplink** URI box.

#### Bot with message
Choose to redirect the user to a specific bot flow or show a predefined bot response.

   * To show a predefined message, select *Text* in **Bot response** and enter the message in **Bot says**. Use variables in the message wherever required.
  
<img src="https://i.imgur.com/gYaHqc9.png" width="70%"/>

   * To execute a bot flow, select *Execute flow* in **Bot response** and choose the flow in **Execute flow**.

   ![](https://i.imgur.com/Tvps1XR.png)

   <img src="https://i.imgur.com/sdu8dWA.png" width="70%"/>
   

   
   




