For an Ionic 4 Cordova implementation of Local Notifications, check out this blog
Ionic 5 is here ! And so is Capacitor 2.0 (beta). In this post you are going to learn how to implement local notifications in Ionic 5 app with Capacitor. We will see a variety of notification types that can be generated using Local Notifications. We will use a simple Cordova plugin, that works for Capacitor as well, and test the functionality on an Android and iOS app.
Complete code of this blog post can be found at this github repo — ionic-5-local-notifications
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 5apps. First, let’s see what Ionic 5 is all about.
What is Ionic?
You probably already know about Ionic, but I’m putting it here just for the sake of beginners. Ionic is a complete open-source SDK for hybrid mobile app development created by Max Lynch, Ben Sperry and Adam Bradley of Drifty Co. in 2013. Ionic provides tools and services for developing hybrid mobile apps using Web technologies like CSS, HTML5, and Sass. Apps can be built with these Web technologies and then distributed through native app stores to be installed on devices by leveraging Cordova.
So, in other words — If you create Native apps in Android, you code in Java. If you create Native apps in iOS, you code in Obj-C or Swift. Both of these are powerful but complex languages. With Cordova (and Ionic) you can write a single piece of code for your app that can run on both iOS and Android (and windows!), that too with the simplicity of HTML, CSS, and JS.
Ionic’s latest version — Ionic 5, was released in March 2020, and is what we are using for this blog post.
Capacitor — How is it different from Cordova ?
Cordova helps build Ionic web app into a mobile device installable app. But there are some limitations of Cordova, which Capacitor tries to overcome with a new App workflow.
Here are the differences between Cordova and Capacitor
- Capacitor considers each platform project a source asset instead of a build time asset. That means, Capacitor wants you to keep the platform source code in the repository, unlike Cordova which always assumes that you will generate the platform code on build time
- Because of the above, Capacitor does not use
config.xml
or a similar custom configuration for platform settings. Instead, configuration changes are made by editingAndroidManifest.xml
for Android andInfo.plist
for Xcode - Capacitor does not “run on device” or emulate through the command line. Instead, such operations occur through the platform-specific IDE. So you cannot run an Ionic-capacitor app using a command like
ionic run ios
. You will have to run iOS apps using Xcode, and Android apps using Android studio - Since platform code is not a source asset, you can directly change the native code using Xcode or Android Studio. This give more flexibility to developers
In essence, Capacitor is like a fresh, more flexible version of Corodva.
Plugins
Cordova and Ionic Native plugins can be used in Capacitor environment. However, there are certain Cordova plugins which are known to be incompatible with Capacitor. For Local Notification functionality, we’ll use the cordova-plugin-local-notifications.
Structure of the post
I will go ahead in step-by-step fashion so you can follow easily
- Create a basic Ionic 5 Capacitor app
- Install Local Notification plugin and make imports
- Implement your first Local Notification, use data from notification
- Build your app on iOS and Android and test
- Implement various types of Local Notifications
Let’s start with creating a simple Ionic 5 app
Step 1 — Create a basic Ionic 5 app
To create a basic Ionic 5 Capacitor app, follow these steps
- Make sure you have node installed in the system (I used V10.15.3 at the time of this blog post, but latest stable version is 12.x)
- Install ionic cli using npm (my Ionic CLI version is 5.3.0 and Ionic Framework is V5.0.5)
- Create an Ionic app using
ionic start
You can create a blank
starter for the sake of this tutorial. On running ionic start ionic-5-local-notifications blank —-capacitor
, node modules will be installed. Once the installation is done, run your app on browser using
$ ionic serve
The app will launch on browser. You can go to Inspect → Device Mode to see the code in a mobile layout.
The --capacitor
flag attaches Capacitor to your Ionic app automatically. If you forget to do it while creating the app, you can do it later by running
$ ionic integrations enable capacitor
You can create a basic layout for triggering Local Notifications. All the real action will happen when we build the app for device (iOS).
The layout here is taken from Ionic 5 Full App from Enappd 🙏
Next we’ll add the Local Notifications plugin to our app.
Step 2 — Install Local Notification plugin and make imports
To implement Local Notifications you need to add cordova-plugin-local-notifications
plugin to the app. Add the plugin using
$ ionic cordova plugin add cordova-plugin-local-notification
$ npm install @ionic-native/local-notifications
This will install the plugin in your app. Next, import the plugin in app.module.ts
and in the pages you want to use it.
import { LocalNotifications} from '@ionic-native/local-notifications/ngx'
Also, include LocalNotifications
in @ngModule
providers list.
@NgModule({
....,
providers: [
...,
LocalNotifications,
...],
})
Now you are ready to implement Local notifications in your Ionic 5 app.
Step 3 — Implement your first Local Notification
Local Notification implementation is very easy once you import the plugin correctly. Head to your home.page.ts
created with the app. Create a function to schedule
your first local notification like this
Super easy, right ? This will create a local notification and it will appear in your device’s status bar as an icon. You can check the full notification in your device’s notification tray.
Let’s dive deeper into the details of the notification object, and learn what all options are available
- id — ID of the notifications
-
title — Title of the notification, shown in larger font. If no
title
is provided, app’s name is shown astitle
- text — Message of the notification. Shown in smaller font. It can be of multiple lines as well. Can be an array of messages as well. We’ll see that in later section
- sound — location of sound file to be played with notification
- data — additional data you can send along with notification in JSON format
- icon — location or URL of icon shown with the notification
- silent — (boolean) whether notification should be silent or not
- trigger — custom trigger time of notification, can be given in various formats. We’ll see this in later section
- attachments — Attached images to be sent with notification
- progressBar — progress-bar options for Local notifications
- group — define the group name to group similar notifications together
- summary — summary of grouped notifications
- smallIcon — Small icon shown for group notifications or custom notifications
- sticky — whether the notification should be sticky or dismissible
- autoClear — If yes, make the notification automatically dismissed when the user touches it (Android only)
-
lockscreen — If set to
true
the notification will be shown in its entirety on all lock-screens. If set tofalse
it will not be revealed on a secure lock-screen. (Android only) - channel — Specifies the channel the notification should be delivered on (Android only)
- foreground — If the notification should show up on app’s foreground
- timeoutAfter — Specifies a duration in milliseconds after which this notification should be canceled, if it is not already canceled (Android only)
- launch — Specifies whether a click on the notification causes the app to open in foreground
- priority — Integers between -2 and 2, whereas -2 is minimum and 2 is maximum priority
-
led — to set LED options of the device. You can set
color
,on
andoff
properties - vibrate — (boolean) — Whether notification should vibrate the device
- color — RGB value for the background color of the smallIcon (Android only)
- badge — The number currently set as the badge of the app icon in Springboard (iOS) or at the right-hand side of the local notification (Android). Default: 0 (which means don’t show a number)
… and few more options. That’s a lot !!!
This is a really powerful and detailed plugin. You can make very good use of the plugin to supplement push notifications, and make your app interactive.
Step 4 — Build your app on Android and test
If you have carried out the above steps correctly, Android build should be a breeze.
Run the following command to create Android platform
$ ionic cordova platform add android
Once platform is added, run the app on device (Make sure you have a device attached to the system).
$ ionic cordova run android
Once your app is up and running on the device, you can start testing all the functions. The GIF shown above is taken from a real Android device 😎
Step 5 — Implement various types of Local Notifications
The GIF in previous section might not have impressed you a lot. So let’s have a look at the variety of notifications and actions you can perform with this plugin
Local notification in foreground
Just add foreground:true
in notification trigger call, and your notification will show up in the foreground, just like Whatsapp !
Get Data from Notification Click
As we saw earlier, the data
field of notification contains certain data in JSON format. We can extract this data using notification events
. For our purpose, we will use click
event.
I will subscribe to the click
event before scheduling the notification. Then on clicking the notification, the event
will be triggered and we will get data in console. I will also show the data in an alert, just for demo. After the alert, we will unsubscribe from the listener. The complete code for this will be
The sequence will look like this
Multiple Notification at once
Just send multiple local notifications in an array inside the schedule
Delayed Local Notifications
You can also delay a notification or send it at a particular time. This way, you can even schedule notifications daily, weekly etc.
E.g. For demo purpose, we’ll trigger a notification after 5000 ms of button click, but it will be taken as a date object. Just add the following option in notification options
trigger: { at: new Date(new Date().getTime() + 5000) },
Local Notification with Progress Bar
You can also display a local notification with a progress bar. This is useful in cases like when you are performing a long background task.
Just add following to notification options object (will show a 20% progress)
progressBar: { value: 20 }
iOS progress bar notification are not that impressive though
Local Notification with multi-line message
You can make the notification message multi-line by adding new line characters. E.g.
text: '4:15 - 5:15 PM\nBig Conference Room'
Local Notification with Image and Action buttons
To add a large image, you can add this to the notification options (yes, kitten photo 😛
attachments: ['http://placekitten.com/g/300/200']
For action buttons, you can add this to the options
actions: [
{ id: 'yes', title: 'Yes' },
{ id: 'no', title: 'No' }
]
An action generally has the following structure —
id?: string;
title?: string;
foreground?: boolean;
launch?: boolean;
ui?: string;
needsAuth?: boolean;
icon?: string;
choices?: string[];
editable?: boolean;
submitTitle?: string;
type?: ILocalNotificationActionType;
This will create a notification with YES and NO buttons
I was not able to get the photo in iOS, probably because of http
, though the action buttons do appear and work
Local Notifications with Input
You can also generate local notification accepting input text in notification tray itself. This comes in handy in chat applications. This is all you need to add to the notification options
actions: [{
id: 'reply',
type: ILocalNotificationActionType.INPUT,
title: 'Reply'
}]
To use ILocalNotificationActionType
, you will have to import it first in the page using
import { ILocalNotificationActionType } from '@ionic-native/local-notifications/ngx';
The result will look like this
Local Notifications with Grouping
At times, you receive many notifications from the same app. E.g. your email app, or chat app. You would like to group these together so as to not take a lot of space in notification tray. You can do this easily with local notifications using the following option
this.localNotifications.schedule([
{ id: 0, title: 'Design team meeting' },
{ id: 1, summary: 'me@gmail.com', group: 'email', groupSummary: true },
{ id: 2, title: 'Please take all my money', group: 'email' },
{ id: 3, title: 'A question regarding this plugin', group: 'email'},
{ id: 4, title: 'Wellcome back home', group: 'email' }
]);
The group:'email'
creates a group with similar notifications which have group:email
. Here’s how it looks
You see the four emails grouped together, with one as a header. Other notification is shown as separate notification. Same for iOS
The group notification do come in annoyingly though in iOS 🙈
Conclusion
In this post, we learnt how to use Local Notification in Ionic 5 Capacitor apps to generate a lot of different types of notifications. These include action buttons, input text, images, multiple notifications, grouping etc. With local notifications, you can save a lot on server push notifications. Plus it gives you the ability to schedule regular notifications as well.
We tested the apps on Android device and iOS simulator to validate the working. I think this is an awesome plugin, and you should definitely use it in your apps if possible.
Complete code of this blog post can be found at this github repo — ionic-5-local-notifications
Next Steps
Now that you have learned the implementation of Local Notifications in Ionic 5, you can also try following blogs. These are written for Ionic 4, but will work nicely for Ionic 5 as well.
- Ionic 4 Payment Gateways — Stripe | PayPal | Apple Pay | RazorPay
- Ionic 4 Charts with — Google Charts | HighCharts | d3.js | Chart.js
- Ionic 4 Social Logins — Facebook | Google | Twitter
- Ionic 4 Authentications — Via Email | Anonymous
- Ionic 4 Features — Geolocation | QR Code reader | Pedometer
- Media in Ionic 4 — Audio | Video | Image Picker | Image Cropper
- Ionic 4 Essentials — Native Storage | Translations | RTL
- Ionic 4 messaging — Firebase Push | Reading SMS
- Ionic 4 with Firebase — Basics | Hosting and DB | Cloud functions
If you need a base to start your next Ionic 5 app, you can make your next awesome app using Ionic 5 Full App
Top comments (0)