PubNub Logo Docs
Support Contact Sales Login Try Our APIs

›PUSH NOTIFICATIONS

Collapse all
Dark mode

Back to Home

Overview

  • In-App Chat

Chat Components

  • Overview
  • REACT

    • React Components

    ANDROID

    • Getting Started
    • UI Components
    • UI Theming
    • Data Components
    • Chat Provider
    • Message Reactions
    • Message Menu

    IOS

    • Getting Started
    • UI Components
    • UI Theming
    • Data Components
    • Chat Provider

SDKs

  • Overview
  • USERS

    • Setup
    • Metadata
    • Permissions
    • Presence
    • Mentions

    CHANNELS

    • Types and Names
    • Metadata
    • Subscriptions
    • Memberships

    MESSAGES

    • Sending Messages
    • Message History
    • Unread Counts
    • File Upload
    • Typing Indicators
    • Read Receipts
    • Emoji Reactions
    • Update Messages
    • Delete Messages
    • External Storage

    PUSH NOTIFICATIONS

    • Overview

    MODERATION

    • Profanity Filters
    • Flag Messages
    • Ban Users
    • Mute Users
    • Spam Prevention

    INTEGRATIONS

    • Overview
    • Content Moderation
    • Image Moderation
    • Language Translation
    • Chatbots
    • GIFs
    • Stickers

Moderation Dashboard

  • Overview
  • Getting Started
  • FEATURES

    • Automatic Text Moderation
    • Automatic Image Moderation
    • Manual Message Moderation
    • Manual User Moderation
    • User Management
    • Channel Management
  • Required Configuration

Debug Console
Network Status

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.

Node.js
Swift
Java
C#
Go

Go to SDK

// 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);
}
);

Go to SDK

// 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)")
}
}

Go to SDK

// 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
}
});

Go to SDK

// 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().
}));

Go to SDK

// 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

Go to SDK

// 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);
}
);

Go to SDK

// 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)")
}
}

Go to SDK

// 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
}
});

Go to SDK

// 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) {
}
}

Go to SDK

// 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
JavaScript
Swift
Java
Unity

Go to SDK

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
});

Go to SDK

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)")
}
}

Go to SDK

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());
}
});

Go to SDK

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);
}

});
←External StorageProfanity Filters→
  • Registering mobile device tokens
    • Retrieving device tokens
    • Adding a device token to channels
    • Removing a device token from channels
  • Publishing messages with push payloads
© PubNub Inc. - Privacy Policy