To send a push notification, your app collects a unique device token from the user. Your backend server stores this token and uses a service like Firebase Cloud Messaging (FCM) or Apple Push Notification Service (APNs) to send messages. The app receives and displays the notification, even running in the background.
Steps to send push notifications
- Use Firebase Cloud Messaging (FCM) or Apple Push Notification Service (APNs).
- Get device tokens from users and store them securely.
- Set up a backend server to send notifications via FCM/APNs APIs.
- Format payload (title, message, data) in JSON.
- Authenticate using API keys (FCM) or certificates (APNs).
- Handle received notifications in the app (foreground/background logic)
Sending push notifications with PubNub
Integrating PubNub for push notifications allows you to deliver real-time mobile and desktop alerts across Android, iOS, and Web platforms.
Want to give it a try? Check our Push Notifications DEMO
Overview of PubNub Push Notifications
PubNub's Mobile Push Gateway bridges native message publishing with third-party push notification services, including Apple Push Notification service (APNs) and Firebase Cloud Messaging (FCM). This integration enables you to send push alerts to users even when they are offline or not actively using your app.
Setting Up PubNub Push Notifications
Step 1: Create a PubNub Account and Configure Keys
- Sign Up: Create an account on the PubNub Admin Portal.
- Create an App: Within the dashboard, create a new app to obtain your Publish Key and Subscribe Key.
- Enable Push Notifications: Navigate to your app's Keyset settings and enable Mobile Push Notifications.
Step 2: Integrate with Push Notification Services
- For Android (FCM):
- Firebase Setup: Register your app with Firebase to obtain the google-services.json file.
- PubNub Configuration: In the PubNub Admin Portal, add your FCM Server Key to enable communication between PubNub and FCM.
- For iOS (APNs):
- Apple Developer Setup: Configure your app to support push notifications and obtain the necessary APNs certificates.
- PubNub Configuration: Upload your APNs certificate to the PubNub Admin Portal to establish a connection between PubNub and APNs.
Step 3: Register Device Tokens with PubNub
Each device registers its unique push token with PubNub and associates it with specific channels. This ensures that when a message is published to a channel, all devices registered to that channel receive the notification.
Example for Android (Java):
// Initialize PubNub
PNConfiguration pnConfig = new PNConfiguration();
pnConfig.setPublishKey("YOUR_PUBNUB_PUBLISH_KEY");
pnConfig.setSubscribeKey("YOUR_PUBNUB_SUBSCRIBE_KEY");
pnConfig.setUuid("DEVICE_UUID");
PubNub pubnub = new PubNub(pnConfig);
// Register device token
pubnub.addPushNotificationsOnChannels()
.pushType(PNPushType.FCM)
.channels(Arrays.asList("news_channel"))
.devicePushToken("DEVICE_FCM_TOKEN")
.async((result, status) -> {
if (!status.isError()) {
Log.d("PUBNUB", "Push registered successfully!");
}
});
Example for iOS (Swift):
// Initialize PubNub
let config = PubNubConfiguration(
publishKey: "YOUR_PUBNUB_PUBLISH_KEY",
subscribeKey: "YOUR_PUBNUB_SUBSCRIBE_KEY",
uuid: "DEVICE_UUID"
)
let pubnub = PubNub(configuration: config)
// Register device token
pubnub.addPushNotificationsOnChannels(
channels: ["news_channel"],
pushType: .apns,
devicePushToken: deviceToken
) { result in
switch result {
case .success:
print("Push registered successfully!")
case .failure(let error):
print("Error: \(error.localizedDescription)")
}
}
Step 4: Publishing Messages
To send a push notification, publish a message to the desired channel. PubNub will forward this message to the associated push notification service (FCM or APNs), and deliver it to the device.
Java Example:
pubnub.publish()
.channel("news_channel")
.message(Collections.singletonMap("text", "Hello, World!"))
.async((result, status) -> {
if (!status.isError()) {
Log.d("PUBNUB", "Message published successfully!");
} else {
Log.e("PUBNUB", "Publish error: " + status.getErrorData().getInformation());
}
});
Check full technical documentation on how to send push notifications
Technical Details
Message Payloads: when publishing messages intended for push notifications, ensure the payload aligns with the requirements of the target platform:
- FCM: Use the "
pn_gcm
" key in your message payload. - APNs: Use the "
pn_apns
" key in your message payload.
JSON Example Payload:
{
"pn_gcm": {
"notification": {
"title": "New Alert!",
"body": "You have a new message."
}
},
"pn_apns": {
"aps": {
"alert": {
"title": "New Alert!",
"body": "You have a new message."
},
"sound": "default"
}
}
}
API Limits
PubNub enforces certain limits to ensure optimal performance:
- Requests Per Second (RPS): API requests are limited to 25 requests per second (RPS). If your application needs a higher limit, reach out to PubNub Support
- Publish Rate: recommended to publish 10-15 messages per second per channel.
Latency
PubNub is designed for low-latency message delivery:
- Average Latency: 50% of messages are delivered in under 20 milliseconds.
- Intranet Latency: Below 1 millisecond.
- WAN Latency: Sub-30 milliseconds.