Push notifications
PubNub's Mobile Push Gateway enables you to easily integrate with third-party services including FCM (Firebase Cloud Messaging) and APNs (Apple Push Notification service) to trigger push notifications.
Responding to a message immediately can make all the difference. If a prospective client is looking for information or a critical service is down, you want to be in the loop 24/7. You can use PubNub to send your users push notifications to keep them up to date when their chat window is closed, they are not actively using your app, or even when they are offline. This way, your users can stay informed about important messages you don't want them to miss.
Registering mobile device tokens
Mobile Push allows you to associate devices (push tokens) with channels. When a message is published to a push-enabled channel, all associated devices receive that message via their respective push service (FCM or APNs).
Note that you must first enable Push Notifications from the Admin Portal to use them in your app. For more details on working with mobile push notifications, refer to our Push Notification documentation.
Retrieving device tokens
Before you can use either service, you must be registered to use Firebase Cloud Messaging (FCM) or the Apple Push Notification service (APNs).
Each device that runs your app has a unique device token, which you need to register to be able to send push notifications. You can obtain the token from your user's device using either your native app, or Cordova/PhoneGap with the Cordova Push plugin.
To retrieve an iOS device token, follow this Apple guide.
To retrieve an Android registration token, follow this Google guide.
Adding a device token to channels
This method associates a device token with one or more channels.
// FCM
pubnub.push.addChannels(
{
channels: ["chats.room1", "chats.room2", "alerts.system"],
device: deviceToken,
pushGateway: "gcm",
},
function(status) {
console.log(status);
}
);
// APNs2
pubnub.push.addChannels(
{
channels: ["chats.room1", "chats.room2", "alerts.system"],
device: deviceToken,
pushGateway: "apns2",
environment: "production", // Required for APNs2
topic: "com.mycompany.mybundleid" // Required for APNs2
},
function(status) {
console.log(status);
}
);
// APNs2
pubnub.modifyAPNSDevicesOnChannels(
byRemoving: [],
thenAdding: ["chats.room1", "chats.room2", "alerts.system"],
device: deviceToken,
on: "com.mycompany.mybundleid",
environment: .production
) { result in
switch result {
case let .success(response):
print("Successful Push Modification Response: \(response)")
case let .failure(error):
print("Failed Push List Response: \(error.localizedDescription)")
}
}
// FCM
pubnub.addPushNotificationsOnChannels()
.pushType(PNPushType.FCM)
.channels(Arrays.asList("chats.room1", "chats.room1", "alerts.system"))
.deviceId(deviceToken)
.async(new PNCallback<PNPushAddChannelResult>() {
@Override
public void onResponse(PNPushAddChannelResult result, PNStatus status) {
// Handle response
}
});
// APNs2
pubnub.addPushNotificationsOnChannels()
.pushType(PNPushType.APNS2)
.channels(Arrays.asList("chats.room1", "chats.room1", "alerts.system"))
.deviceId("deviceToken")
.topic("com.mycompany.mybundleid")
.environment("production")
.async(new PNCallback<PNPushAddChannelResult>() {
@Override
public void onResponse(PNPushAddChannelResult result, PNStatus status) {
// Handle response
}
});
// FCM
pubnub.AddPushNotificationsOnChannels()
.PushType(PNPushType.FCM)
.Channels(new string[] { "chats.room1", "chats.room2", "alerts.system" })
.DeviceId(deviceToken)
.Execute(new PNCallback<PNPushAddChannelResult>((r, s) => {
// This does not return actionable data. Be sure to check the status
// on the outcome of the operation by checking the status.isError().
}));
// FCM
pn.AddPushNotificationsOnChannels().
Channels([]string{"ch1"}).
DeviceIDForPush("device_id").
PushType(pubnub.PNPushTypeFCM).
Execute()
Removing a device token from channels
This method disassociates a device token from one or more channels.
// FCM
pubnub.push.removeChannels({
channels: ['ch-1', 'ch-2'],
device: 'myDeviceId',
pushGateway: 'gcm',
}, (status) => {
if (status.error) {
console.log('operation failed w/ status: ', status);
} else {
console.log('operation done!');
}
});
// APNs2
pubnub.push.removeChannels({
channels: ['ch-1', 'ch-2'],
device: 'myDeviceId',
pushGateway: 'apns2',
environment: 'production', // Required for APNs2
topic: 'com.mycompany.mybundleid' // Required for APNs2
},
function(status) {
console.log(status);
}
);
// APNs2
pubnub.removeAPNSDevicesOnChannels(
["ch-1"],
for: deviceToken,
on: "com.app.bundle",
environment: .production
) { result in
switch result {
case let .success(channels):
print("The list of channels disabled for push: \(channels)")
case let .failure(error):
print("Failed Push List Response: \(error.localizedDescription)")
}
}
// FCM
pubNub.removePushNotificationsFromChannels()
.channels(Arrays.asList("ch-1", "ch-2"))
.pushType(PNPushType.FCM)
.deviceId("myDeviceId")
.async(new PNCallback<PNPushRemoveChannelResult>() {
@Override
public void onResponse(PNPushRemoveChannelResult result, PNStatus status) {
// Handle status, response
}
});
// FCM
pubnub.RemovePushNotificationsFromChannels()
.DeviceId("myDeviceId")
.Channels(new string[] {
"ch-1",
"ch-2"
})
.PushType(PNPushType.FCM)
.Execute(new DemoPushRemoveChannel());
public class DemoPushRemoveChannel : PNCallback<PNPushRemoveChannelResult> {
public override void OnResponse(PNPushRemoveChannelResult result, PNStatus status) {
}
}
// FCM
pn.RemovePushNotificationsFromChannels().
Channels([]string{"ch-1", "ch-2"}).
DeviceIDForPush("myDeviceId").
PushType(pubnub.PNPushTypeFCM).
Execute()
Publishing messages with push payloads
If you want to trigger push notifications, include one or both endpoint keys (pn_apns
or pn_gcm
) in your message before you send it to PubNub. Users connected to PubNub channels receive the message
portion of the payload, and each third-party endpoint receives the data encapsulated in its associated endpoint key:
- APNs devices receive only the data within the
pn_apns
key - FCM devices receive only the data within the
pn_gcm
key
const messagePayload = {
"pn_apns":{
"aps":{
"alert":{
"title":"Chat invitation",
"body":"John invited you to chat"
}
},
"pn_push":[
{
"push_type":"alert",
"targets":[
{
"environment":"production",
"topic":"BUNDLE_ID_FOR_APP_1"
}
],
"version":"v2"
}
]
},
"pn_gcm":{
"notification":{
"title":"Chat invitation",
"body":"John invited you to chat",
"sound":"default"
}
},
"text":"Hello all!"
};
pubnub.publish({
message: messagePayload,
channel: 'ch-1',
}, (status) => {
// Handle publish status
});
let message = ["text": "John invited you to chat", "room": "chats.room1"]
let payload = PubNubPushMessage(
apns: PubNubAPNSPayload(
aps: APSPayload(alert: .object(.init(title: "Chat invite")), sound: .string("default")),
pubnub: [.init(targets: [.init(topic: "com.example.chat", environment: .production)])],
payload: ""
),
fcm: PubNubFCMPayload(
payload: "",
target: .topic(""),
notification: FCMNotificationPayload(title: "Chat invite", body: "John invited you to chat"),
android: FCMAndroidPayload(notification: FCMAndroidNotification(sound: "default"))
),
additional: message
)
print(payload)
// Publish on channel
pubnub.publish(
channel: "inbox.user123",
message: payload
) { result in
switch result {
case let .success(response):
print("Successful Response: \(response)")
case let .failure(error):
print("Failed Response: \(error.localizedDescription)")
}
}
PushPayloadHelper pushPayloadHelper = new PushPayloadHelper();
// Set up FCM parameters (FCMPayload)
PushPayloadHelper.FCMPayload fcmPayload = new PushPayloadHelper.FCMPayload();
PushPayloadHelper.FCMPayload.Notification fcmNotification =
new PushPayloadHelper.FCMPayload.Notification()
.setTitle("Chat invite")
.setBody("John invited you to chat");
fcmPayload.setNotification(fcmNotification);
// Set FCM payload
pushPayloadHelper.setFcmPayload(fcmPayload);
// Create the APS alert title/body
JsonObject apsAlertData = new JsonObject();
apsAlertData.addProperty("title", "Chat invite");
apsAlertData.addProperty("body", "John invited you to chat");
// Define APS
PushPayloadHelper.APNSPayload.APS aps = new PushPayloadHelper.APNSPayload.APS()
.setAlert(apsAlertData)
.setSound("default");
PushPayloadHelper.APNSPayload apnsPayload = new PushPayloadHelper.APNSPayload()
.setAps(aps);
// Set APNs2 Configurations as a list
apnsPayload.setApns2Configurations(Arrays.asList(
new PushPayloadHelper.APNSPayload.APNS2Configuration()
.setVersion("v2")
.setTargets(Arrays.asList(
new PushPayloadHelper.APNSPayload.APNS2Configuration.Target()
.setEnvironment(PNPushEnvironment.PRODUCTION)
.setTopic("com.example.chat")
))));
// Set APNs payload
pushPayloadHelper.setApnsPayload(apnsPayload);
// Common payload for real-time PubNub subscribe
Map<String, Object> commonPayload = new HashMap<>();
commonPayload.put("text", "John invited you to chat");
commonPayload.put("room", "chats.room1");
pushPayloadHelper.setCommonPayload(commonPayload);
// Build the payload
// Returns a Map which can be used directly as the message for the pubnub.publish() method
Map<String, Object> payload = pushPayloadHelper.build();
System.out.println(payload);
// Publish on channel
pubnub.publish()
.channel("inbox.user123")
.message(payload)
.async(new PNCallback<PNPublishResult>() {
@Override
public void onResponse(PNPublishResult result, PNStatus status) {
if (!status.isError()) {
System.out.println("pub timetoken: " + result.getTimetoken());
}
System.out.println("pub status code: " + status.getStatusCode());
}
});
Dictionary<string, string> payload = new Dictionary<string, string>();
payload.Add("pn_apns", "<apple payload>");
payload.Add("pn_gcm", "<google payload>");
pubnub.Publish()
.Channel("chats.room1")
.Message(payload)
.Async((result, status) => {
if (!status.Error) {
Debug.Log(string.Format("DateTime {0}, In Publish Example, Timetoken: {1}", DateTime.UtcNow , result.Timetoken));
} else {
Debug.Log(status.Error);
Debug.Log(status.ErrorData.Info);
}
});