Using Local Notifications In Your NativeScript Mobile App

When developing mobile apps, at some point in time you may find yourself needing to show a background notification to your users. There are two types of notifications, one being the push notification which is sent from a remote server and the other being local notifications that are triggered from within the application.

We’re going to focus on local notifications here.

So when might you need to use a local notification? There are many scenarios. Let’s say you’re creating an app that communicates with iBeacons. When you’re within proximity maybe you want to trigger a notification to the user. There are many other scenarios that I won’t get into.

We’re going to see a basic example on how to use local notifications in a NativeScript Android and iOS mobile application.

Let’s start by creating a new NativeScript project. From your Command Prompt (Windows) or Terminal (Mac and Linux), execute the following commands:

tns create NotificationProject
cd NotificationProject
tns platform add ios
tns platform add android

It is important to note that if you’re not using a Mac, you cannot add and build for the iOS platform.

To make use of local notifications we’re going to use a plugin. If we really wanted to we could include the native code for notifications directly within our JavaScript, but for convenience we want to use a plugin.

We’re going to use the nativescript-local-notifications plugin by Eddy Verbruggen. To install it, execute the following from the Terminal or Command Prompt:

tns plugin add nativescript-local-notifications

We can now start developing the application. Before going forward, some code was taken directly from Eddy Verbruggen’s README file. I’ve given it my own flair.

Let’s start by working with our view model which will contain our data. Open the project’s app/main-view-model.js and include the following code:

var Observable = require("data/observable").Observable;
var LocalNotifications = require("nativescript-local-notifications");
var dialogs = require("ui/dialogs");

function doAddOnMessageReceivedCallback() {
    LocalNotifications.addOnMessageReceivedCallback(
        function(notificationData) {
            dialogs.alert({
                title: "Notification received",
                message: "ID: " + notificationData.id +
                "\nTitle: " + notificationData.title +
                "\nBody: " + notificationData.body,
                okButtonText: "Excellent!"
            });
        }
    );
}

function createViewModel() {
    var viewModel = new Observable();

    viewModel.id = 0;
    viewModel.title = "Test Title";
    viewModel.body = "Test Body";
    viewModel.ticker = "Test Ticker";

    doAddOnMessageReceivedCallback();

    viewModel.schedule = function() {
        LocalNotifications.schedule([{
            id: this.id,
            title: this.title,
            body: this.body,
            ticker: this.ticker,
            at: new Date(new Date().getTime() + (10 * 1000))
        }]).then(() => {
            console.log("Notification scheduled");
        }, (error) => {
            console.log("ERROR", error);
        });
    }

    return viewModel;
}

exports.createViewModel = createViewModel;

A lot is going on here so we should probably break it down.

The first part of this file is the doAddOnMessageReceivedCallback function. This is the function that will be called it the notification is clicked. It can be the router to future functionality within your application based on the particular notification. For example maybe you have a chat application and you want to be directed to the particular chat room.

The bulk of our local notification code will be in the createViewModel function. We’ll be returning an Observable that has various variables that will be bound to a UI form. It also contains a schedule function for scheduling the notification itself.

Now we can take a look at the application model which acts as our page controller. Open the project’s app/main-page.js file and include the following code:

var createViewModel = require("./main-view-model").createViewModel;
var LocalNotifications = require("nativescript-local-notifications");

function onNavigatingTo(args) {
    var page = args.object;
    LocalNotifications.requestPermission().then((granted) => {
        if(granted) {
            page.bindingContext = createViewModel();
        }
    })
}

exports.onNavigatingTo = onNavigatingTo;

For iOS you must first ask for permission to use notifications. Before loading the view model that we created previously, we attempt to grant permission. If permission is granted we can proceed as normal. This all happens when the page loads, or in this case the page was navigated to.

Finally we can look at the UI file. Let’s modify our user interface by making the project’s app/main-page.xml file look like the following:

<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="onNavigatingTo">
    <StackLayout>
        <TextField id="id" hint="Numeric ID" text="{{ id }}" />
        <TextField id="title" hint="title" text="{{ title }}" />
        <TextView id="body" hint="body" text="{{ body }}" />
        <TextView id="ticker" hint="ticker" text="{{ ticker }}" />
        <StackLayout orientation="horizontal">
            <Button text="Schedule" tap="{{ schedule }}" />
        </StackLayout>
    </StackLayout>
</Page>

We have a basic form above. There are four text fields, two of which are for multiple lines of text. The text properties use the variables that we bound in the view model file. The button also uses the function that we created in the view model.

At this point we should be good to go!

If you schedule a notification, you can close the application and it will still show at the scheduled time. In iOS, the notification will show regardless if the application is in the foreground or background.

Conclusion

You just saw how to make use of local notifications, not to be confused with push notifications. These notifications have zero dependence on a remote service and can be seen while the application is in the background.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

Search

Follow Us

Subscribe

Subscribe to my newsletter for monthly tips and tricks on subjects such as mobile, web, and game development.

Subscribe on YouTube

Support This Site