Local Notifications

Use local notifications to notify users of alarms, reminders etc.

What is Local Notification ?

We have all heard of notifications, and push notifications mostly. These are the notifications app servers send to apps for regular reminders. For example, a chat app server sends notification to user to update of a latest message. These notifications are received in closed app, minimized app or open app.

Push notifications cause burden on Server, as well as, cost you money if you are using a service like OneSignal etc. Hence, for each action or reminder, you might not want the server to send push notifications to all users. Especially if you have millions of users.

This is where Local Notifications come in handy. These look and feel exactly like push notifications, but are not sent from server. Instead, they are generated locally on your device. E.g. If you want an app to remind you of your tasks at a certain time of the day, it makes sense that the app does so using the in-built clock or timer in the device. The app then sends you Local Notification, which looks same as a push.

You don’t feel the difference between Local and Push notification, and the server saves a lot of overhead.

In this post, we will learn how to implement Local notifications features in Ionic 4 apps. First, let’s see what Ionic 4 is all about.

Capacitor Local Notification API

The Local Notification API provides a way to schedule "local" notifications - notifications that are scheduled and delivered on the device as opposed to "push" notifications sent from a server.

Local Notifications are great for reminding the user about a change in the app since they last visited, providing reminder features, and delivering offline information with the app being in the foreground.

E.g. If you have a game app, you would like to remind users to play every 24 hours or so. So you schedule local notifications for every 24 hours.

Example

import { Plugins } from '@capacitor/core';
const { LocalNotifications } = Plugins;

LocalNotifications.schedule({
  notifications: [
    {
      title: "Title",
      body: "Body",
      id: 1,
      schedule: { at: new Date(Date.now() + 1000 * 5) },
      sound: null,
      attachments: null,
      actionTypeId: "",
      extra: null
    }
  ]
});

Methods

Available methods in this API are

  • areEnabled - Check if local notifications are enabled or not

  • cancel - Cancel one or more scheduled notification

  • getPending - Get a list of all pending (scheduled) notifications

  • schedule - Schedule notification on a given interval or at a particular time

  • addListener("localNotificationReceived") - Listen to a notification received

  • addListener("localNotificationActionPerformed") - Listen to a notification action performed, like tap etc.

More details on the methods are provided in the official documentation

Last updated