Push

Push helps you reach out to your users in a timely fashion with important messages. You can use it to inform users about updates to some piece of data, about new services available nearby or that they are winners in a game. Using Custom server code you can set up triggers which send push notifications to a targeted set of people based on changes in the data you specify.

Kinvey brings Android Push Notifications to you through an integration with Google Cloud Messaging (GCM) and iOS Push Notifications through an integration with AWS SNS. While push notifications can only be configured to be used by either iOS or Android devices, our APIs provide support for registering/unregistering devices and associating them with Kinvey users.

Setup

Console Setup

Android

  1. Navigate to the Firebase Console and follow the guide to create a new project or select an existing project.
  2. Click the gear icon in the top left of the side menu and select Project Settings.
  3. Click on the Cloud Messaging tab and write down the Sender ID and Server Key (formerly known as Project Number).
  4. On Kinvey's console select your App.
  5. Navigate to Engagement and select Push.
  6. Click Configure Push.
  7. In the Android section, fill in the Sender ID and Server Key fields with the respective Sender ID and Server Key values obtained in step 3.
  8. Click Save

iOS

When using Apple Push Notification Service (APNS) you will get two push certificates; one for development and one for production/ad-hoc. These certificates require push notifications to be sent to different servers depending on if your app is in development or production.

The production certificate is only usable if your app is in the App Store.

  1. Generate an Apple Push Certificate .p12 file for your app (instructions).
  2. After you export the .p12 file, on Kinvey's console navigate to Engagement and select Push.
  3. Click Configure Push.
  4. In the iOS section drag your .p12 file generated in step 1 where it says Drag here or click to upload a .p12 file.
  5. Click Save
  6. When you are ready to deploy your app, use your production/ad-hoc certificate. Export the .p12 file, and upload that to our service. Then select production as the certificate type and click Save. Deploying your application is a one-time action and cannot be undone.

Setup Push Notification Modules

In order to receive push notifications, you will need to install the react-native-push-notification npm module. For iOS an additional peer dependency is needed - @react-native-community/push-notification-ios.

A comprehensive Push Notification Setup guide for the separate platforms, can be found in the Optional Install Push Notification section of React Native SDK README

Registering the Device

The device needs to be registered to receive push notifications through Kinvey. There must be a logged-in user when registering. This user will be linked to the device, allowing you to send targeted push notifications.

To register the device, initialize the Push module:

import * as Push from 'kinvey-react-native-sdk/lib/push';

const promise = Push.register((message: any) => {
  alert(message);
})
  .then((deviceToken: string) => {
    // ...
  })
  .catch((error: Error) => {
    // ...
  });
var Push = require('kinvey-react-native-sdk/lib/push');

var promise = Push.register((message: any) => {
  alert(message);
})
  .then(function(deviceToken) {
    // ...
  })
  .catch(function(error) {
    // ...
  });

The message callback is not strictly necessary. However, registering it here gives you the ability to compose push notifications with advanced options and data and is highly recommended, if only limited to the sendPayload() and broadcastPayload() sending methods.

For Android notifications, the message represents the message that appears in the notification drawer and has a predefined set of keys such as title and body. See the sendPayload() and broadcastPayload() method descriptions to learn how to set these. Read detailed information about the Google-defined keys in the Firebase Cloud Messaging documentation.

The following represents the object that the SDK will send to GCM after you set the payload using an SDK method.

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Portugal vs. Denmark",
      "body":"The game is over"
    },
    "data":{
      "Score":"2:1",
      "Room":"PortugalVsDenmark"
    }
  }
}

For iOS notifications, the message represents the JSON dictionary required by APNs. It encompasses the aps dictionary, which contains Apple-defined keys, and any number of custom keys. See the sendPayload() and broadcastPayload() method descriptions to learn how to set these.

The alert, badge, and sound keys are default settings valid for all iOS notifications. Their values can be overridden on message level using the keys within the aps dictionary.

The following represents the object that the SDK will send to APNs after you set the payload using an SDK method.

{
    "aps" : {
        "alert" : {
            "title" : "Portugal vs. Denmark",
            "body" : "The game is over",
            "action-loc-key" : "PLAY"
        },
        "badge" : 5
    },
    "Score" : "2:1",
    "Room" : "PortugalVsDenmark"
}

Triggering Push Notifications

In addition to using the Console, you can trigger a push notification from Business Logic or a Flex service. This approach allows for greater flexibility as it makes it possible to schedule push notifications, to tie them down to various data events, and to set advanced options supported by Android and iOS.

You can send push notification from either collection hooks, effectively tying the notification to a data event, or custom endpoints which you can call manually or programmatically when needed.

The methods for sending push notifications are provided by the push module available in both Business Logic and the Flex SDK. They include send(), sendMessage(), sendPayload(), broadcastPayload(), and broadcastMessage(). Check the module's reference for detailed information.

The following code uses the onPreSave() before-processing collection hook to send a simple push notification to all users who fancy the winning team. Instead of saving any data to the data store, this request just causes the push notification to be sent.

function onPreSave(request,response,modules){
   var userCollection = modules.collectionAccess.collection('user')
   , utils = modules.utils
   , push = modules.push
   , template = '{{name}}, the {{team}} just won!'
   , pushedMessageCount = 0
   , userCount;

   // Find all users whose favoriteTeam matches
   // the incoming request's winning team.
   userCollection.findAsync({"favoriteTeam": request.body.winningTeam})
   .then(function(userDocs){
     // Total number of messages to send
     userCount = userDocs.length;

     // Each message is customized
     userDocs.forEach(function(doc){
       var values = {
          name: doc.givenName,
          team: doc.favoriteTeam
       };

       // Render the message to send
       var message = utils.renderTemplate(template, values);

       // Send the push
       push.send(doc, message);

       // Keep track of how many pushes are sent
       pushedMessageCount++;

       // Reduce the number of users left to push to
       userCount--;
       if (userCount <= 0){
         // All pushes sent out, complete the request
         response.body = {
             "message": "Attempted to push "
             + pushedMessageCount
             + " messages."
         };
         response.complete(200);
        }
     });
  })
  .catch(function(error){
      response.body = error;
      response.complete(400);
  });
}

The body of the request must have a winningTeam property. For example:

{
  "winningTeam": "Boston Red Sox"
}

Users are expected to have a givenName property and a favoriteTeam property.

The Push notification will be similar to:

Joe, the Kansas City Royals just won!

In case you want to set advanced message options such as title, body, badge, and sound or to send custom data to your app, you have to use the sending methods that accept advanced payloads. These include sendPayload() and broadcastPayload() (see API reference: Business Logic | Flex).

In your Business logic, you could have the following onRequest() handler which constructs the payloads for iOS and Android and then sends the new product message using sendPayload():

function onRequest(request, response, modules) {
    var push = modules.push;
    var users = [];
    var collectionAccess = modules.collectionAccess;
    var iOSAps = {
        alert: "We have a new product: Honey Bread! Tap to add to shopping list",
        badge: 2,
        sound: "notification.wav"
    }
    var iOSExtras = {Product: "Honey Bread", Price: 1.25, Quantity: 1};
    var androidPayload = {
        "_rawPayload": {
            "notification": {
                "title": "We have a new product - Honey Bread",
                "body": "Tap to add to shopping list",
                "color": "#444687"
            },
            "data": {
                "Product": "Honey Bread",
                "Price": 1.25,
                "Quantity": 1
            }
        }
    }
    collectionAccess.
        collection('user').
        find({ 'WantsNewProductsAlert': true }, function (err, res) {
            if (err) {
                response.complete(400);
            }
            else {
                push.sendPayload(
                    res,
                    iOSAps,
                    iOSExtras,
                    androidPayload,
                    function (err,  success) {
                        if (err) {
                            response.complete(200);
                        }
                        else {
                            response.complete(200);
                        }
                    }
                )
            }
        })
}

Unregistering the Device

The unregister operation allows you to remove the current device from the user account's list of registrations, effectively stopping the user from receiving push notifications on the device. The operation is useful when the user has opted out of receiving this kind of notifications or for another reason. Unregister requires an active user. It will return an error if you call it after logging out the user.

import * as Push from 'kinvey-react-native-sdk/lib/push';

const promise = Push.unregister()
  .then(() => {
    // ...
  })
  .catch((error: Error) => {
    // ...
  });
var Push = require('kinvey-react-native-sdk/lib/push');

var promise = Push.unregister()
  .then(function() {
    // ...
  })
  .catch(function(error) {
    // ...
  });