Push notifications
Mobile Push Notifications feature enables you to easily integrate with third-party services including FCM (Firebase Cloud Messaging) and APNs (Apple Push Notification service) to trigger mobile 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 mobile 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 Mobile 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 mobile 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.
- Node.js
- Swift
- Java
- C#
- Go
// FCM
pubnub.push.addChannels(
{
channels: ["chats.room1", "chats.room2", "alerts.system"],
device: deviceToken,
pushGateway: "gcm",
},
function(status) {
console.log(status);
}
);
// APNs2
pubnub.push.addChannels(
{
show all 25 lines// 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)")
}
show all 16 lines// FCM
pubnub.addPushNotificationsOnChannels()
.pushType(PNPushType.FCM)
.channels(Arrays.asList("chats.room1", "chats.room1", "alerts.system"))
.deviceId(deviceToken)
.async(result -> { /* check result */ });
// APNs2
pubnub.addPushNotificationsOnChannels()
.pushType(PNPushType.APNS2)
.channels(Arrays.asList("chats.room1", "chats.room1", "alerts.system"))
.deviceId("deviceToken")
.topic("com.mycompany.mybundleid")
.environment("production")
.async(result -> { /* check result */ });
// 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.
- Node.js
- Swift
- Java
- C#
- Go
// 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({
show all 25 lines// 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(result -> { /* check result */ });
// 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 mobile push notifications, include one or both endpoint keys (pn_apns
or pn_fcm
) 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_fcm
key
- JavaScript
- Swift
- Java
- Unity
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"
show all 40 lineslet 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
show all 32 linesPushPayloadHelper 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
show all 56 linesDictionary<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);
}
show all 16 lines