Home

Awesome

Push Plugin for NativeScript


This plugin is deprecated. Feel free to use the Firebase Plugin for implementing push notifications in your NativeScript app. If you already have an app that use the Push Plugin, read the migrate-to-firebase doc for initial guidance.


Build Status

The code for the Push Plugin for NativeScript.

<!-- TOC depthFrom:2 depthTo:3 --> <!-- /TOC -->

Installation

In the Command prompt / Terminal navigate to your application root folder and run:

tns plugin add nativescript-push-notifications

Configuration

Android

See the Android Configuration for using Firebase Cloud Messaging for information about how to add Firebase to your project.

The plugin will default to version 12.0.1 of the firebase-messaging SDK. If you need to change the version, you can add a project ext property firebaseMessagingVersion:

    // in the root level of /app/App_Resources/Android/app.gradle:
    project.ext {
        firebaseMessagingVersion = "+" // OR the version you wish
    }

iOS

Usage

Using the plugin in Android

Add code in your view model or component to subscribe and receive messages (don't forget to enter your Firebase Cloud Messaging Sender ID in the options of the register method):

TypeScript

import * as pushPlugin from "nativescript-push-notifications";
private pushSettings = {
    senderID: "<ENTER_YOUR_PROJECT_NUMBER>", // Required: setting with the sender/project number
    notificationCallbackAndroid: (stringifiedData: String, fcmNotification: any) => {
        const notificationBody = fcmNotification && fcmNotification.getBody();
        this.updateMessage("Message received!\n" + notificationBody + "\n" + stringifiedData);
    }
};
pushPlugin.register(pushSettings, (token: String) => {
    alert("Device registered. Access token: " + token);;
}, function() { });

Javascript

var pushPlugin = require("nativescript-push-notifications");
var pushSettings = {
        senderID: "<ENTER_YOUR_PROJECT_NUMBER>", // Required: setting with the sender/project number
        notificationCallbackAndroid: function (stringifiedData, fcmNotification) {
            var notificationBody = fcmNotification && fcmNotification.getBody();
            _this.updateMessage("Message received!\n" + notificationBody + "\n" + stringifiedData);
        }
    };
pushPlugin.register(pushSettings, function (token) {
    alert("Device registered. Access token: " + token);
}, function() { });

Using the plugin in iOS

Add code in your view model or component to subscribe and receive messages:

TypeScript

import * as pushPlugin from "nativescript-push-notifications";
const iosSettings = {
    badge: true,
    sound: true,
    alert: true,
    interactiveSettings: {
        actions: [{
            identifier: 'READ_IDENTIFIER',
            title: 'Read',
            activationMode: "foreground",
            destructive: false,
            authenticationRequired: true
        }, {
            identifier: 'CANCEL_IDENTIFIER',
            title: 'Cancel',
            activationMode: "foreground",
            destructive: true,
            authenticationRequired: true
        }],
        categories: [{
            identifier: 'READ_CATEGORY',
            actionsForDefaultContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER'],
            actionsForMinimalContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER']
        }]
    },
    notificationCallbackIOS: (message: any) => {
        alert("Message received!\n" + JSON.stringify(message));
    }
};

pushPlugin.register(iosSettings, (token: String) => {
    alert("Device registered. Access token: " + token);

    // Register the interactive settings
    if(iosSettings.interactiveSettings) {
        pushPlugin.registerUserNotificationSettings(() => {
            alert('Successfully registered for interactive push.');
        }, (err) => {
            alert('Error registering for interactive push: ' + JSON.stringify(err));
        });
    }
}, (errorMessage: any) => {
    alert("Device NOT registered! " + JSON.stringify(errorMessage));
});

Javascript

var pushPlugin = require("nativescript-push-notifications");
var iosSettings = {
    badge: true,
    sound: true,
    alert: true,
    interactiveSettings: {
        actions: [{
            identifier: 'READ_IDENTIFIER',
            title: 'Read',
            activationMode: "foreground",
            destructive: false,
            authenticationRequired: true
        }, {
            identifier: 'CANCEL_IDENTIFIER',
            title: 'Cancel',
            activationMode: "foreground",
            destructive: true,
            authenticationRequired: true
        }],
        categories: [{
            identifier: 'READ_CATEGORY',
            actionsForDefaultContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER'],
            actionsForMinimalContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER']
        }]
    },
    notificationCallbackIOS: function (data) {
        alert("message", "" + JSON.stringify(data));
    }
};

pushPlugin.register(iosSettings, function (data) {
    alert("Device registered. Access token" + data);

    // Register the interactive settings
        if(iosSettings.interactiveSettings) {
            pushPlugin.registerUserNotificationSettings(function() {
                alert('Successfully registered for interactive push.');
            }, function(err) {
                alert('Error registering for interactive push: ' + JSON.stringify(err));
            });
        }
}, function() { });

API Reference

Methods

register(options, successCallback, errorCallback) - subscribe the device with Apple/Google push notifications services so the app can receive notifications

OptionPlatformTypeDescription
senderIDAndroidStringThe Sender ID for the FCM project. This option is required for Android.
notificationCallbackAndroidAndroidFunctionCallback to invoke, when a push is received on Android.
badgeiOSBooleanEnable setting the badge through Push Notification.
soundiOSBooleanEnable playing a sound.
alertiOSBooleanEnable creating a alert.
clearBadgeiOSBooleanEnable clearing the badge on push registration.
notificationCallbackIOSiOSFunctionCallback to invoke, when a push is received on iOS.
interactiveSettingsiOSObjectInteractive settings for use when registerUserNotificationSettings is used on iOS.

The interactiveSettings object for iOS can contain the following:

OptionTypeDescription
actionsArrayA list of iOS interactive notification actions.
categoriesArrayA list of iOS interactive notification categories.

The actions array from the iOS interactive settings contains:

OptionTypeDescription
identifierStringRequired. String identifier of the action.
titleStringRequired. Title of the button action.
activationModeStringSet to either "foreground" or "background" to launch the app in foreground/background and respond to the action.
destructiveBooleanEnable if the action is destructive. Will change the action color to red instead of the default.
authenticationRequiredBooleanEnable if the device must be unlocked to perform the action.
behaviorStringSet if the action has a different behavior - e.g. text input.

The categories array from the iOS interactive settings contains:

OptionTypeDescription
identifierStringRequired. String identifier of the category.
actionsForDefaultContextArrayRequired. Array of string identifiers of actions.
actionsForMinimalContextArrayRequired. Array of string identifiers of actions.

For more information about iOS interactive notifications, please visit the Apple Developer site

var settings = {
    badge: true,
    sound: true,
    alert: true,
    interactiveSettings: {
        actions: [{
            identifier: 'READ_IDENTIFIER',
            title: 'Read',
            activationMode: "foreground",
            destructive: false,
            authenticationRequired: true
        }, {
        identifier: 'CANCEL_IDENTIFIER',
            title: 'Cancel',
            activationMode: "foreground",
            destructive: true,
            authenticationRequired: true
        }],
        categories: [{
            identifier: 'READ_CATEGORY',
            actionsForDefaultContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER'],
            actionsForMinimalContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER']
        }]
    },
    notificationCallbackIOS: function(message) {
        alert(JSON.stringify(message));
    }
};


pushPlugin.register(settings,
    // Success callback
    function(token){
        // Register the interactive settings
        if(settings.interactiveSettings) {
            pushPlugin.registerUserNotificationSettings(function() {
                alert('Successfully registered for interactive push.');
            }, function(err) {
                alert('Error registering for interactive push: ' + JSON.stringify(err));
            });
        }
    },
    // Error Callback
    function(error){
        alert(error.message);
    }
);

unregister(successCallback, errorCallback, options) - unsubscribe the device so the app stops receiving push notifications. The options object is the same as on the register method

ParameterPlatformTypeDescription
successCallbackiOSFunctionCalled when app is successfully unsubscribed. Has one object parameter with the result.
successCallbackAndroidFunctionCalled when app is successfully unsubscribed. Has one string parameter with the result.
errorCallbackAndroidFunctionCalled when app is NOT successfully unsubscribed. Has one parameter containing the error.
optionsAndroidFunctionCalled when app is NOT successfully unsubscribed. Has one parameter containing the error.
pushPlugin.unregister(
    // Success callback
    function(result) {
        alert('Device unregistered successfully');
    },
    // Error Callback
    function(errorMessage) {
        alert(errorMessage);
    },
    // The settings from the registration phase
    settings
);

areNotificationsEnabled(successCallback) - check if push notifications are enabled (iOS only, always returns true on Android)

ParameterPlatformTypeDescription
successCallbackiOS/AndroidFunctionCalled with one boolean parameter containing the result from the notifications enabled check.
pushPlugin.areNotificationsEnabled(function(areEnabled) {
        alert('Are Notifications enabled: ' + areEnabled);
    });

Android only

onMessageReceived(callback) DEPRECATED - register a callback function to execute when receiving a notification. You should set this from the notificationCallbackAndroid registration option instead

ParameterTypeDescription
stringifiedDataStringA string containing JSON data from the notification
fcmNotificationObjectiOS/Android

The fcmNotification object contains the following methods:

MethodReturns
getBody()String
getBodyLocalizationArgs()String[]
getBodyLocalizationKey()String
getClickAction()String
getColor()String
getIcon()String
getSound()String
getTag()String
getTitle()String
getTitleLocalizationArgs()String[]
getTitleLocalizationKey()String

onTokenRefresh(callback) - register a callback function to execute when the old token is revoked and a new token is obtained. Note that the token is not passed to the callback as an argument. If you need the new token value, you'll need to call register again or add some native code to obtain the token from FCM

ParameterTypeDescription
callbackFunctionCalled with no arguments.
pushPlugin.onTokenRefresh(function() {
        alert("new token obtained");
});

iOS only

registerUserNotificationSettings(successCallback, errorCallback) - used to register for interactive push on iOS

ParameterTypeDescription
successCallbackFunctionCalled when app is successfully unsubscribed. Has one object parameter with the result.
errorCallbackFunctionCalled when app is NOT successfully unsubscribed. Has one parameter containing the error.

Troubleshooting

In case the application doesn't work as expected. Here are some things you can verify

Troubleshooting issues in Android

Troubleshooting issues in iOS

Android Configuration for using Firebase Cloud Messaging

The nativescript-push-notifications module for Android relies on the Firebase Cloud Messaging (FCM) SDK. In the steps below you will be guided to complete a few additional steps to prepare your Android app to receive push notifications from FCM.

  1. Add the google-services.json file

    To use FCM, you need this file. It contains configurations and credentials for your Firebase project. To obtain this follow the instructions for adding Firebase to your project from the official documentation. Scroll down to the Manually add Firebase section.

    Place the file in your app's App_Resources/Android folder

  2. Obtain the FCM Server Key (optional)

    This key is required to be able to send programmatically push notifications to your app. You can obtain this key from your Firebase project.

Receive and Handle Messages from FCM on Android

The plugin allows for handling data, notification, and messages that contain both payload keys which for the purposes of this article are reffered to as mixed. More specifics on these messages are explained here.

The plugin extends the FirebaseMessagingService and overrides its onMessageReceived callback. In your app you need to use the notificationCallbackAndroid setting when calling the register method of the plugin.

The behavior of the callback in the module follows the behavior of the FCM service.

Handling Data Messages

The notificationCallbackAndroid method of the plugin is called each time a data notification is received.

If the app is stopped or suspended, NO notification is constructed and placed in the tray. Tapping the app icon launches the app and invokes the notificationCallbackAndroid callback where you will receive the notification data.

If the app is active and in foreground, the notificationCallbackAndroid callback is invoked immediately with the notification data (fcmNotification).

Handling Notification Messages

If the app is active and in foreground, it invokes the notificationCallbackAndroid callback with two arguments (stringifiedData, fcmNotification).

If the app is in background, a notification is put in the tray. When tapped, it launches the app, but does not invoke the notificationCallbackAndroid callback.

Handling Mixed Messages

Mixed messages are messages that contain in their load both data and notification keys. When such message is received:

Example of handling the data part in the application resume event (e.g. the app was brought to the foreground from the notification):

application.on(application.resumeEvent, function(args) {
    if (args.android) {
        var act = args.android;
        var intent = act.getIntent();
        var extras = intent.getExtras();
        if (extras) {
            // for (var key in extras) {
            //     console.log(key + ' -> ' + extras[key]);
            // }
            var msg = extras.get('someKey');
        }
    }
});

Parameters of the notificationCallbackAndroid Callback

Depending on the notification event and payload, the notificationCallbackAndroid callback is invoked with two arguments.

Setting Notification Icon and Color

The plugin automatically handles some keys in the data object like message, title, color, smallIcon, largeIcon and uses them to construct a notification entry in the tray.

Custom default color and icon for notification messages can be set in the AndroidManifest.xml inside the application directive:

<meta-data
    android:name="com.google.firebase.messaging.default_notification_icon"
    android:resource="@drawable/ic_stat_ic_notification" />
<meta-data
    android:name="com.google.firebase.messaging.default_notification_color"
    android:resource="@color/colorAccent" />

For more info visit the Edit the app manifest article.

Contribute

We love PRs! Check out the contributing guidelines. If you want to contribute, but you are not sure where to start - look for issues labeled help wanted.

Get Help

Please, use github issues strictly for reporting bugs or requesting features. For general questions and support, check out Stack Overflow or ask our experts in NativeScript community Slack channel.