In this guide, we will review different scenarios for sending notifications with Notify, like using identity and tags, and show different useful tricks on how to receive Push notifications on iOS and Android devices.
Note, that to be able to send notifications, you first need to create bindings and to receive Push notifications on both iOS and Android, you first need to configure Push Notifications and register a device to receive Push Notifications.
Check out our other guides, that explain how to do that:
Once you have that done, you will be able to send and receive notifications. So let's get to it!
We'll want to send a POST
request to Twilio from notify.js
in our server app. The request should authenticate using your Twilio Account SID and Auth Token.
It should also identify who to send a notification to by either their
identity or tags.
We'll use identity if we want a notification to be sent to all devices with Bindings associated with a given identity.
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createNotification() {11const notification = await client.notify.v112.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")13.notifications.create({14body: "Hello Bob",15identity: ["00000001"],16});1718console.log(notification.sid);19}2021createNotification();
1{2"sid": "NTb8021351170b4e1286adaac3fdd6d082",3"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",4"service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",5"date_created": "2016-03-24T23:42:28Z",6"identities": [7"jing"8],9"tags": [],10"segments": [],11"priority": "high",12"ttl": 2419200,13"title": "test",14"body": "Hello Bob",15"sound": null,16"action": null,17"data": null,18"apn": null,19"fcm": null,20"gcm": null,21"sms": null,22"facebook_messenger": null,23"alexa": null24}
If we want to send a notification to a particular Binding of a user, we can use identity and tags together.
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createNotification() {11const notification = await client.notify.v112.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")13.notifications.create({14body: "Hello Bob",15identity: ["00000001"],16tag: ["preferred_device"],17});1819console.log(notification.sid);20}2122createNotification();
1{2"sid": "NTb8021351170b4e1286adaac3fdd6d082",3"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",4"service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",5"date_created": "2016-03-24T23:42:28Z",6"identities": [7"jing"8],9"tags": [],10"segments": [],11"priority": "high",12"ttl": 2419200,13"title": "test",14"body": "Hello Bob",15"sound": null,16"action": null,17"data": null,18"apn": null,19"fcm": null,20"gcm": null,21"sms": null,22"facebook_messenger": null,23"alexa": null24}
It is best practice, and also potentially required by law in certain jurisdictions, for you to have consent from your end users before sending messages to them, and you should respect your end users' choice to not receive messages from you. It is also important to make sure your database is up to date. This is particularly important for number-based communications like SMS because over time phone numbers may be reassigned to different individuals. If your database is out of date, you could inadvertently send a message to someone who did not consent but was reassigned a phone number that was previously subscribed to your service by another person. Check out the Twilio Marketplace for Add-ons from our partners that can help you keep your database up to date.
Twilio recommends that you consult with your legal counsel to make sure that you are complying with all applicable laws in connection with communications you transmit using Twilio.
In this section, we will review how to receive notifications with an iOS device and go through different scenarios of receiving notifications like App in the Background, App in the Foreground or using apn payload to display a badge.
iOS has a native listener functions that fire whenever a notification is received. This happens in our AppDelegate.
There are a number of ways we can potentially receive a notification depending on the state of our app, our device type and channel-specific payload specified in notifications. Let's take a look at some of these scenarios.
When your app is in the foreground, the message is not shown in the device's notification center; instead, it is delivered to your app and needs to be processed. Please note that the app may stay in foreground mode for up to 10 minutes after switching to another application.
To send a notification to an iOS device displaying a badge, you need to use apn payload.
Notifications resource has channel specific parameters (payload) where you can specify information on how the user should be notified of a Push Notification, including displaying a badge on the app icon. To do that, just add "badge" : X
(X being the number the app icon will be badged with).
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createNotification() {11const notification = await client.notify.v112.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")13.notifications.create({14apn: {15aps: {16alert: {17title: "Bob alert",18body: "Bob, you just received a badge",19},20badge: 1,21},22},23identity: ["00000001"],24});2526console.log(notification.sid);27}2829createNotification();
1{2"sid": "NTb8021351170b4e1286adaac3fdd6d082",3"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",4"service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",5"date_created": "2016-03-24T23:42:28Z",6"identities": [7"jing"8],9"tags": [],10"segments": [],11"priority": "high",12"ttl": 2419200,13"title": "test",14"body": "body",15"sound": null,16"action": null,17"data": null,18"apn": {19"aps": {20"alert": {21"title": "Bob alert",22"body": "Bob, you just received a badge"23},24"badge": 125}26},27"fcm": null,28"gcm": null,29"sms": null,30"facebook_messenger": null,31"alexa": null32}
Note, the device you want to send notifications to has to be registered for receiving Push notifications, including badges. See how to do that in our Registering for iOS Push Notifications guide
Now all you need to do is implement badge count, to pass on the correct badge number depending on the logic of your application.
In this section, we will review how to receive notifications with an Android device and go through different scenarios of receiving notifications like App in the Background, App in the Foreground.
Android has a native listener functions that fire whenever a notification is received. This happens in our MyFcmListenerService.
1private static final String TAG = "MyFcmListenerService";2@Override3public void onMessageReceived(RemoteMessage message) {4Map<String,String> data = message.getData();5String body = data.get("twi_body");6String title = data.get("twi_title");7Log.d(TAG, "From: " + from);8Log.d(TAG, "Body: " + body);9}10}11
The notification will arrive in JSON format and contains the message body as a String that we can then use locally.
Now let's see how notifications can be received depending on the state of your app.
In the Notification page, you can see how Notification request attributes are mapped to channel-specific parameters.
The notification is delivered to onMessageReceived of the FcmListenerService. The data key-value pairs can be found in the data bundle, but the key-value pairs of the notification bundle are not available.
To get a more in-depth look at the Notifications resources check out our REST API Guide.