Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Sending and Receiving Notifications


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!


Table of Contents

table-of-contents page anchor


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(link takes you to an external page). 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.

Send a Notification (identity)

send-a-notification-identity page anchor
Node.js
Python
C#
Java
Go
PHP
Ruby
twilio-cli
curl

_11
// Download the helper library from https://www.twilio.com/docs/node/install
_11
// Find your Account SID and Auth Token at twilio.com/console
_11
// and set the environment variables. See http://twil.io/secure
_11
const accountSid = process.env.TWILIO_ACCOUNT_SID;
_11
const authToken = process.env.TWILIO_AUTH_TOKEN;
_11
const client = require('twilio')(accountSid, authToken);
_11
_11
client.notify.v1.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
_11
.notifications
_11
.create({body: 'Hello Bob', identity: ['00000001']})
_11
.then(notification => console.log(notification.sid));

Output

_24
{
_24
"sid": "NTb8021351170b4e1286adaac3fdd6d082",
_24
"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_24
"service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_24
"date_created": "2016-03-24T23:42:28Z",
_24
"identities": [
_24
"jing"
_24
],
_24
"tags": [],
_24
"segments": [],
_24
"priority": "high",
_24
"ttl": 2419200,
_24
"title": "test",
_24
"body": "Hello Bob",
_24
"sound": null,
_24
"action": null,
_24
"data": null,
_24
"apn": null,
_24
"fcm": null,
_24
"gcm": null,
_24
"sms": null,
_24
"facebook_messenger": null,
_24
"alexa": null
_24
}

If we want to send a notification to a particular Binding of a user, we can use identity and tags together.

Send a Notification (Identity and Tag)

send-a-notification-identity-and-tag page anchor
Node.js
Python
C#
Java
Go
PHP
Ruby
twilio-cli
curl

_15
// Download the helper library from https://www.twilio.com/docs/node/install
_15
// Find your Account SID and Auth Token at twilio.com/console
_15
// and set the environment variables. See http://twil.io/secure
_15
const accountSid = process.env.TWILIO_ACCOUNT_SID;
_15
const authToken = process.env.TWILIO_AUTH_TOKEN;
_15
const client = require('twilio')(accountSid, authToken);
_15
_15
client.notify.v1.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
_15
.notifications
_15
.create({
_15
body: 'Hello Bob',
_15
identity: ['00000001'],
_15
tag: ['preferred_device']
_15
})
_15
.then(notification => console.log(notification.sid));

Output

_24
{
_24
"sid": "NTb8021351170b4e1286adaac3fdd6d082",
_24
"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_24
"service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_24
"date_created": "2016-03-24T23:42:28Z",
_24
"identities": [
_24
"jing"
_24
],
_24
"tags": [],
_24
"segments": [],
_24
"priority": "high",
_24
"ttl": 2419200,
_24
"title": "test",
_24
"body": "Hello Bob",
_24
"sound": null,
_24
"action": null,
_24
"data": null,
_24
"apn": null,
_24
"fcm": null,
_24
"gcm": null,
_24
"sms": null,
_24
"facebook_messenger": null,
_24
"alexa": null
_24
}

(warning)

Warning

Make sure you have consent from users to receive notifications.

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.


Receiving Notifications on iOS

receiving-notifications-on-ios page anchor

iOS has a native listener functions that fire whenever a notification is received. This happens in our AppDelegate.

Receiving a Notification in iOS

receiving-a-notification-in-ios page anchor
Objective-C
Swift

_10
-(void) application:(UIApplication *) application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo {
_10
NSLog(@"The notification message is: %@", [userInfo valueForKeyPath:@"aps.alert"]);
_10
}


iOS Notification Scenarios

ios-notification-scenarios page anchor

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.

App is in the Background

app-is-in-the-background page anchor
  • If it's an alert notification, it will show on the home screen and in the notification center. The notification can be retrieved by parsing the launch options dictionary in application:willFinish LaunchingWithOptions: and application:didFinishLaunchingWithOptions
  • If it's a silent notification, it will be delivered to application:didReceiveRemoteNotification:fetchCompletionHandler: and no alert will be raised

App is in the Foreground

app-is-in-the-foreground page anchor

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.

  • The application:didReceiveRemoteNotification:fetchCompletionHandler: method is called but no alert will be raised.

To send a notification to an iOS device displaying a badge, you need to use apn payload.

Notify Sending and Receiving Notifications - displaying iOS badge.

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

Send a Detailed Notification with Badge

send-a-detailed-notification-with-badge page anchor
Node.js
Python
C#
Java
Go
PHP
Ruby
twilio-cli
curl

_19
// Download the helper library from https://www.twilio.com/docs/node/install
_19
// Find your Account SID and Auth Token at twilio.com/console
_19
// and set the environment variables. See http://twil.io/secure
_19
const accountSid = process.env.TWILIO_ACCOUNT_SID;
_19
const authToken = process.env.TWILIO_AUTH_TOKEN;
_19
const client = require('twilio')(accountSid, authToken);
_19
_19
client.notify.v1.services('ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
_19
.notifications
_19
.create({apn: {
_19
aps: {
_19
alert: {
_19
title: 'Bob alert',
_19
body: 'Bob, you just received a badge'
_19
},
_19
badge: 1
_19
}
_19
}, identity: ['00000001']})
_19
.then(notification => console.log(notification.sid));

Output

_32
{
_32
"sid": "NTb8021351170b4e1286adaac3fdd6d082",
_32
"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_32
"service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
_32
"date_created": "2016-03-24T23:42:28Z",
_32
"identities": [
_32
"jing"
_32
],
_32
"tags": [],
_32
"segments": [],
_32
"priority": "high",
_32
"ttl": 2419200,
_32
"title": "test",
_32
"body": "body",
_32
"sound": null,
_32
"action": null,
_32
"data": null,
_32
"apn": {
_32
"aps": {
_32
"alert": {
_32
"title": "Bob alert",
_32
"body": "Bob, you just received a badge"
_32
},
_32
"badge": 1
_32
}
_32
},
_32
"fcm": null,
_32
"gcm": null,
_32
"sms": null,
_32
"facebook_messenger": null,
_32
"alexa": null
_32
}

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

Yes, it's that easy! Now all you need to do is implement badge count, to pass on the correct badge number depending on the logic of your application.


Notifications on Android

notifications-on-android page anchor

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.


Receiving Notifications on Android

receiving-notifications-on-android page anchor

Android has a native listener functions that fire whenever a notification is received. This happens in our MyFcmListenerService.

Receiving a Notification in Android

receiving-a-notification-in-android page anchor

_10
private static final String TAG = "MyFcmListenerService";
_10
@Override
_10
public void onMessageReceived(RemoteMessage message) {
_10
Map<String,String> data = message.getData();
_10
String body = data.get("twi_body");
_10
String title = data.get("twi_title");
_10
Log.d(TAG, "From: " + from);
_10
Log.d(TAG, "Body: " + body);
_10
}
_10
}

The notification will arrive in JSON format and contains the message body as a String that we can then use locally.


Android Notifications Scenarios

android-notifications-scenarios page anchor

Now let's see how notifications can be received depending on the state of your app.

  • Data message (default): If there is only a data bundle then the app is woken up in the background and the onMessageReceived function is called. This is the default behavior in Notify as we map all parameters to the data bundle.
(information)

Info

In the Notification page, you can see how Notification request attributes are mapped to channel-specific parameters.

  • Notification message: If there is nothing in the data section, then it's added to the notification
    center.
  • Hybrid message: If there is a data section and a notification section, then it is added to the notification center and if the user clicks on the notification then the app is woken up and the data bundle is handed to the onMessageReceived function.

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.

What's next


To get a more in-depth look at the Notifications resources check out our REST API Guide.


Rate this page: