Using Local Notifications In Your Ionic 2 Mobile App

A little more than a year ago I wrote a tutorial regarding using local notifications in an Ionic Framework Android and iOS application, but Ionic Framework and AngularJS is rapidly becoming a thing of the past.  Lately, anything Angular 2 is all the rage and that includes frameworks that use it like Ionic 2.  This inspired me to update my previous tutorial for the latest and greatest.

Let’s take a step back though.  Why would one want to use local notifications in their mobile application?  Well, one example might be in iBeacon detection.  An iBeacon comes into range and a notification might show.  That is just one of many examples.  Let’s also not confuse local notifications with push notifications.  Local notifications have no interaction with a service like Firebase Cloud Messaging (FCM) or Apple Push Notification Service (APNS).

We’re going to see how to schedule notifications and perform tasks based on various actions around the notifications.

The application that we’re going to build is very simple.  We’re going to allow notifications to be scheduled five seconds in the future.  When these notifications are clicked, we’ll open the application and show an alert message.  Something like the animated image below.

Ionic 2 Local Notifications

To make this project simple, we’re going to create a fresh Ionic 2 project for Android and iOS.  From your Command Prompt (Windows) or Terminal (Mac and Linux), execute the following:

A few things to note in the above commands.  The --v2 and --typescript tags mean that we’re going to be creating an Ionic 2 project that uses TypeScript.  For this to be possible you need to have the Ionic 2 CLI, not the standard Ionic CLI.  Second, you’ll notice that I’m adding the iOS platform.  You won’t be able to build for iOS unless you have Xcode installed.

With our project created we need to add the plugin responsible for local notifications.  We’re going to use the Apache Cordova local notifications plugin by Sebastián Katzer.  To add this plugin, execute the following:

Time to get down to business in our application.

Most of our development will be TypeScript oriented, with a slight bit of HTML markup.  Let’s start with the TypeScript logic.  Open the project’s app/pages/home/home.ts file and include the following code:

Let’s break down what is happening in the above code.

We’re importing a few components.  We’re importing NavController and Alert for displaying alert dialogs and we’re importing LocalNotifications because we’re going to use Ionic Native to assist with the Apache Cordova plugin.

This brings us to the HomePage class.

Inside the constructor method we are defining any events associated to the notifications.  Think of them as listeners that we’re configuring.  In this case we’re looking out for the click event and showing an alert if it happens.

Finally this takes us to the schedule method.  In it we define some basic things and set the schedule to be five seconds from now.  Nothing particularly complicated.

Now we can take a look at the HTML markup that goes with the TypeScript logic.  Open the project’s app/pages/home/home.html file and include the following markup:

We really just have a single button that calls our schedule method.

Conclusion

We just saw how to use local notifications in an Ionic 2 iOS and Android application.  Local notifications are different from push notifications because they don’t deal with a server.  There are plenty of other events that I didn’t show that you can see in the official plugin documentation.  If you’re looking for local notifications in an Ionic Framework 1 application, check out a previous article I wrote on the topic.

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.

  • Hi Nic, thanks for this!
    Just wanted to point that this code is not updated to Ionic 2.0.0-beta.10, maybe update your CLI?
    Best regards!

    • Damn, I wrote this last week. Sucks that it is already dated. I will upgrade it to work with beta 10, which I’m hoping are only minor changes.

      • Indeed, just the ion-header introduction.
        More changes may come with the implementation of the latest Angular 2 router and forms.
        This release is moving too fast 😀

        • Just updated it, thanks. Was hoping that as beta things would stop changing. Feels like changes should happen in an alpha release or developer preview, but thats just my opinion.

          • Yea, it was supposed to be more stable but I prefer this than have faulty stuff like Angular 2 deprecated ngControl* forever. Better to fix some design now and have a super cool framework henceforth 🙂

          • BTW, Ionic went full typescript, no need of the flag anymore.

          • Good to know, it’s obvious I can’t keep up with all the changes ;-). Are you on the development team?

          • Nope, I just have a project and I’m actively following up the action 😀

          • Awesome. Don’t hesitate to point out my mistakes if something changes. Often I can’t keep up 🙂

  • Suresh

    Hi Nic,
    I have a question on updating the icon on the notification. I tried placing a custom image on the following path for android:
    platforms/android/res/drawable_hdpi..
    and linked it with the icon parameter on the cordova plugin.
    But i always see a blank box. How do we rectify this. What am i doing wrong. Does cordova has any restriction on the file size and the pixel size o this icon image.
    Looking forward to hear from you soon.
    Regards
    Suresh

    • I believe you want to use the absolute path to the file:

      https://github.com/katzer/cordova-plugin-local-notifications#sample

      If you use the file plugin, you should be able to get this information no problem.

      • Suresh

        Hi Nic,
        I already tried with that icon parameter. It does;t work for me. I still only see a blank icon.Below is the link for my source code.
        https://drive.google.com/file/d/0B8wzqavG-4r9R3ItTVhaZDc2U28/view?usp=sharing

        • Sorry, I’ll only look at code that is on GitHub or Pastebin.

          The icon parameter isn’t what I was referring you to. I am saying you probably need to use the absolute path on the file system, the one with file://.

          Best,

          • Suresh

            Hi Nic,
            I tried adding the file path for the image, but i couldn’t see it getting updated. Maybe i have used wrong syntax. I also checked on the plugin page, but i couldn’t find any useful information on the file path. Even the example mentioned in the plugin results the bell symbol on my simulator. Here is my js code
            http://pastebin.com/AAwMMJ5M.
            Let me know if you find any mistakes. Looking forward… thanks in advance.
            Regards
            suresh

          • You shared ionic 1 and angular 1 code. This tutorial is for ionic 2 and angular 2. They are very different.

          • Suresh

            Hi Nic,
            Sorry, My bad. I was suppose to post this on the other tutorial page where you had the local notifications video for the Ionic 1 framework.

  • Olexiy665

    Hi, Nic, many thanks for this) One question: how I can open my application without clicking by push-notification? Or even run my application on schedule, something like alarmclock?)

    • I don’t think you can. Pretty sure that can be considered malicious by the app stores if an app decides when it opens.

      • Olexiy665

        Thank you. But how about Cordova wakeuptimer-plugin. Is there is something similar for Ionic2?

  • moo hyug Ahn

    Hi Nic! really thanks for your article 🙂 I have one question actually. I am trying to use “trigger” event to increase count of badge. schedule function works, but trigger event doesn’t work.. how can i deal with this? i have a code.

    // after local noti alert trigger, badge number increases 1
    LocalNotifications.on(“trigger”, (notification, state) => {
    this.nav.present(alert);
    Badge.increase(1);
    });

    • Anything show up in your logs? Maybe throw some debug logic into the trigger event and see if it fires.

      • moo hyug Ahn

        I put the debug logic and it doesn’t throw out anything..

        • You might want to raise a ticket with the Ionic team. Sounds like there could be a bug with either the Ionic Native component or the underlying Apache Cordova plugin. Lots of moving parts in Ionic applications.

          Best,

  • Can I open the app to a specific page if the app has been closed? I have a click event that fires, and changes the page the app is opened on. This is fine if the app is in the background, but if the app has been closed it only opens to the app homepage.

    • You’ll probably want to save something to storage and in the trigger, look at that data and navigate as necessary.

  • Newbie on Ionic 2. I keep getting error on “Alert.create….” and “navCtrl.present…” Is there something I am missing.

  • Newbie on Ionic 2. I keep getting error on “Alert.create….” and “navCtrl.present…” Is there something I am missing over here?

  • I am a newbie on Ionic 2. I keep getting error on “Alert.create….” and “navCtrl.present…” Is there something I am missing over here?

    • Anyway, got the ‘schedule( )’ function to work. Thanks Nic!

      • Anuradha Sanjeewa Wickramarach

        Alert.create(() => {}) is deprecated. You should be using the AlertController instead.

        • As soon as Ionic 2 stabilizes I will be updating all my articles.

  • ramakrishnan

    hi nic, can u let me know how to inject this ionic-native local notification in ionic v1

  • egvrcn

    Hi Nic, I want to push notification between two separate hours every day.
    I’ve done a lot of research on this topic.
    I could not find a solution.
    For example between 7:00 and 11:00 hours every an hour.
    My code like this:

    $cordovaLocalNotification.add({
    id: id,
    date: alarmTime,
    message:”msg”,
    title: title,
    autoCancel: true,
    every: “day”,

  • Carol Shi

    Hi Nic, local notification worked for my android phone. However it did not work for my ipad. my ipad ios version is 9.3. Can not figure out. Could you give me suggestion?

    • Suresh Palaniappan

      hi any update on this issue. I’m also facing similar issue with my iphone with ios 10.0.1 version..

  • Marc Albert

    Hi,

    Alert is deprecated. You have to use AlertControler. This is the correct code using AlertControler instead of Alert in the file
    “app/pages/home/home.ts” :

    import {Component} from “@angular/core”;
    import {NavController, AlertController } from ‘ionic-angular’;
    import {LocalNotifications} from ‘ionic-native’;

    @Component({
    selector: ‘page-home’,
    templateUrl: ‘home.html’
    })
    export class HomePage {

    constructor(private navController: NavController, private alertCtrl: AlertController) {
    LocalNotifications.on(“click”, (notification, state) => {
    let alert = this.alertCtrl.create({
    title: “Notification Clicked”,
    message: “You just clicked the scheduled notification”,
    buttons: [“OK”]
    });
    alert.present()
    });
    }

    }

    Regards.
    Marc Albert.