Send mobile push notifications

PubNub connects to Android Firebase Cloud Messaging (FCM) and iOS Apple Push Notification service (APNs) for push notifications.

Create provider keys and add them in the Admin Portal.

FCM also supports iOS. Use one provider or both.

Mobile Push Notifications view in Admin Portal showing provider key fields and save controls

Before you begin, make sure you have:

  • Access to the Admin Portal
  • Platform credentials (APNs key for iOS, Firebase key for Android)
  • A mobile app that requests push notification permissions

A device push token is a unique ID from APNs or FCM that targets a specific app install.

Request a device push token

Register each device with its push provider to get a device push token. Refer to the Android, iOS, and Firebase for iOS documentation for setup.

Register and cache the device push token

After you obtain a device push token, ensure your app always uses the current token. Collect, replace, and cache the device push token. For caching, use UserDefaults on iOS and SharedPreferences on Android.

To create the cache:

let tokenDispatch = DispatchQueue(label: "com.pubnub.deviceToken", attributes: .concurrent)
var cachedToken: Data? {
get {
var token: Data?
tokenDispatch.sync {
token = UserDefaults.standard.data(forKey: "com.pubnub.deviceToken")
}
return token
}
set {
tokenDispatch.async(flags: .barrier) {
UserDefaults.standard.set(newValue, forKey: "com.pubnub.deviceToken")
}
}
}

Next, update the cached device push token when it changes.

For more information regarding registering token, go to Apple Docs.

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let oldDeviceToken = self.cachedToken
guard deviceToken != oldDeviceToken else { return }
self.cachedToken = deviceToken

updateAPNSDevicesOnChannels(
pushChannels.allObjects, newDevice: deviceToken, oldDevice: oldDeviceToken,
on: "com.mycompany.mybundleid", environment: .production
) { result in
switch result {
case .success: print("Successfully updated channels with new token")
case let .failure(error): print("Failed to update device token due to: \(error)")
}
}
}

Connect the device to a channel

Initialize your PubNub client with your subscribe and publish keys. Mark specific channels as push channels. In the examples below, ch1 and ch2 are added as push channels.

if let deviceToken = (UIApplication.shared.delegate as? AppDelegate)?.cachedToken {
pubnub.addAPNSDevicesOnChannels(
["ch1", "ch2"],
device: deviceToken,
on: "com.mycompany.mybundleid",
environment: .production
) { result in
switch result {
case let .success(channelsAdded):
channelsAdded.forEach { (UIApplication.shared.delegate as? AppDelegate)?.pushChannels.update(with: $0) }
case let .failure(error): print("Failed to add Push due to: \(error.localizedDescription)")
}
}
}

Build the push notification message

Specify APNs (pn_apns) or FCM (pn_fcm) in the payload. For APNs, set the environment (development or production) and the app bundle ID (topic).

For Apple Push Notification Service:

{
"text": "John invited you to chat",
"pn_apns": {
"aps": {
"alert": {
"title": "Chat Invitation",
"body": "John invited you to chat"
}
},
"pn_push":[
{
"push_type": "alert",
"auth_method": "token",
"targets":[
{
show all 25 lines

For Firebase:

let message = ["text": "John invited you to chat"]

let pushPayload = PubNubPushMessage(
fcm: PubNubFCMPayload(
payload: nil,
target: .topic("invitations"),
apns: FCMApnsConfig(
headers: [
"apns-push-type": "alert", "apns-topic": "com.mycompany.mybundleid", "apns-priority": "10"
],
payload: APSPayload(alert: .object(.init(title: "Chat Invitation", body: "John invited you to chat")))
)
),
additional: message
)

Send the push notification

Use publish to send the push. Publish on the same channels you registered for mobile push.

pubnub.publish()
.channel("ch1")
.message(pushPayload)
.async(result -> { /* check result */ });
Last updated on