Send mobile push notifications

One of the features that PubNub offers is the ability to connect to Android and iOS push notification services.

This is done by creating a key from one, or both, of those providers and adding it to your PubNub Admin Portal.

It's possible to use Google/Firebase in iOS applications, so the choice is yours whether you want to manage both services.

PubNub Portal Push Key location

Request a push notification token for the device

For every device that you'd like to receive a push notification on, you must register with the notification provider. Refer to the Android, iOS, and Firebase for iOS documentation on how to get this set up.

Register and cache your token

Now that you're set up with your token, you'll need to make sure as tokens are created by your service, that your app is always using the correct token. This means collecting, replacing, and caching. For caching you can use UserDefaults for iOS and SharedPreferences for 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")
}
}
}

Now, let's catch and replace the tokens as they come in.

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

For your app to know that what you're sending is going to be a push notification, you'll need to define certain channels to be push channels. In the code examples below you'll see Ch1 and Ch2 as the two channels being added.

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

Building the push notification message

When constructing the Push message you wish to send you need to specify whether you're using Apple Push Notification pn_apns or Firebase (Google) Cloud Message pn_fcm in your payload. APN will require you to define the environment (development or production) and the Bundle ID of your app using 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

Just like when sending any other message with PubNub, we use the publish method to mobile push notifications. For mobile push notifications to work we must send a message on the channels that we registered for mobile push notifications in the previous steps.

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