Brief
TLDR; Notifications have proven to be a great way to boost engagements in mobile apps. This can be achieved using local or push notifications. The major distinction between these is that in push notifications, the message being displayed is triggered or sent from a remote server whereas local notifications are triggered by the mobile device locally. This article supplements the Capacitor and Ionic framework documentation on local notifications using Ionic React with Capacitor native plugins.
Assumptions
You have:
- Knowledge of writing Ionic apps using React
- Basic knowledge of Capacitor native plugins
- Existing app needing integration of local notifications (Optional)
Setup
If you haven't already, you would need to install Capacitor. See the documentation on the integration of Capacitor into Ionic here: https://capacitorjs.com/docs/getting-started/with-ionic
Code
We would be carrying out the integration of local notifications on a sample component called Home.tsx
. The local notifications logic would reside in Notifications.ts
Notifications.ts
import { Plugins, LocalNotification } from '@capacitor/core';
const { LocalNotifications } = Plugins;
class Notifications {
public async schedule(hour: number, minute: number) {
try {
// Request/ check permissions
if (!(await LocalNotifications.requestPermission()).granted) return;
// Clear old notifications in prep for refresh (OPTIONAL)
const pending = await LocalNotifications.getPending();
if (pending.notifications.length > 0)
await LocalNotifications.cancel(pending);
await LocalNotifications.schedule({
notifications: [{
title: 'Triumph30',
body: doc.data().message,
id: i,
schedule: {
on: { // swap this out for at or every as needed
hour,
minute
}
}
}]
});
} catch (error) {
console.error(error);
}
}
}
export default new Notifications()
Triggering notifications can be split into 2 phases:
- Requesting permission
- Scheduling notification
In order to trigger a notification, permission must be obtained for either android and ios. This can be done by calling the asynchronous requestPermission()
method on the LocalNotifications
import as seen above. This promise resolves with an object {granted: "boolean"}
. If the permission has been granted by the user or granted previously, granted is true, else false.
With permissions granted, notifications can be scheduled. Calling the schedule()
method passing in an object with a notifications field schedules notifications. The notifications field accepts an array of objects (notifications to be scheduled) with the following key fields (Refer to the documentation or intellisense on vscode for more):
{
title: "string",
body: "message body as string",
id: "unique number",
schedule: "object specifying how notification should run"
}
Schedule Types
There are 3 broad types of schedule:
Running the notification at an exact time [repeatedly]. This is the easiest notification to set up. The schedule object is declared as follows:
schedule: { on: { day: "number|undefined", month: "number|undefined", year: "number|undefined", hour: "number|undefined", minute: "number|undefined", } }
For example, Setting only the minute would trigger a notification at that minute every hour while setting the hour along, would trigger every day while setting the day along, would trigger every month and so on.
Running a notification [repeatedly] at a duration between the present time and a specified time. This can be achieved using a combination of the
at
field andrepeats
as follows:schedule: { at: "Date Object", repeats: "Boolean" }
For example, if the current time is 08:00 AM, Setting
at
as 09:00 AM would trigger a notification at 09:00 AM. To have it repeat hourly, set the repeats boolean field to true else leave it out or set to false.Running a notification at a specified
"year" | "month" | "two-weeks" | "week" | "day" | "hour" | "minute" | "second"
interval. In this method, the number of times and the kind of interval is specified as follows:schedule: { every: "year" | "month" | "two-weeks" | "week" | "day" | "hour" | "minute" | "second", count: "number" }
For example, specifying
every
as "week" andcount
as 4 would send out notifications on a weekly basis for a total of 4 times only.
Home.tsx
import React from 'react';
import notifications from './Notifications.ts';
const Home: React.FC<any> = () => {
return (
<IonPage>
<IonHeader mode="ios">
<IonToolbar mode="md">
<MessageBtn />
<Logo />
<IonTitle>Home</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent>
<div>
<IonButton color="tertiary" onClick={() => notifications.schedule(8,0)}>
Schedule Notification
</IonButton>
</div>
</IonContent>
</IonPage>
)
}
Hope this helps with your integration of Local notifications into Ionic React using Capacitor. Please leave your comments for clarification. ๐
Get managed hosting and database for your NodeJS, Python, Go applications and more. SQL and NoSQL databases all included under one plan. Start for free today! https://zhap.cloud