Friday, September 24, 2021

Implement Local Notifications in Ionic with Capacitor and Example

I started this topic directly from local notification installation. I assume already have angular and ionic setup on your project. Checkout here to complete installation setup.

#Install


npm install @capacitor/local-notifications npx cap sync

#Basic Configuration


Local Notifications needs to be configured with the following options: SmallIcon, IconColor and sound for capactior.

#Example

Add this below json in capacitor.config.json. If need you can change the icon, color and sound.

{ "plugins": { "LocalNotifications": { "smallIcon": "ic_stat_icon_config_sample", "iconColor": "#488AFF", "sound": "notification.wav" } } }

Note : Need to paste the custom icon and sound file in path specified below. then only the sound will work. Icon folder : project-folder/android/app/src/main/res/drawable Sound Folder : project-folder/android/app/src/main/res/raw If you don’t have a folder name with raw in res, then you can create the folder raw inside res. Then paste the sound inside raw.  

Once the above configuration is done, Create Service using the below command. If you create notification as service means you can call this anywhere from your application just use of dependency injection. 

ng g service localnotification

Once created, Imports the local notification package into the service.

import { LocalNotifications } from '@capacitor/local-notifications';


#Check Permission

Need to check notification permission before create notification

return LocalNotifications.checkPermissions().then((res) => { if (res && res.display && res.display == 'denied') { LocalNotifications.requestPermissions().then((res) => { if (res && res.display && res.display == 'denied') { console.log("Need a Notification Permission to Set Reminder."); } }) } });

Both checkPermissions() and requestPermissions() functions return any one state as mentioned below,

'prompt' 'prompt-with-rationale' 'granted' 'denied'



#Create Notification

await LocalNotifications.schedule({ notifications: [{ id: id, title: title, body: description, schedule: { at: new Date(new Date(dateTime).getTime()), }, sound: 'notification.wav' }] });

In notification, 

id should be an integer and unique.  

title Provide the title which you want to show on notification

body Provide the body content which you want to show on notification

schedule Provide the date with time when you want to show the notification. I just used at in my schedule. But in capacitors there will be more options available like on, repeats, every. You can use this option based on your requirement. 

sound if you want to set some custom sound means provide just name of the file with extension .wav (no need to provide file path here), otherwise remove this sound from local notification array, notification rings with default sound.

Note : Need to paste the custom sound file in path below specified. then only the sound will work. Sound File : project-folder/android/app/src/main/res/raw If you don’t have a folder name with raw in res, then you can create the folder raw inside res. Then paste the sound inside raw.


#Example


Below the Service file I created for local notification.

import { Injectable } from '@angular/core';

import { LocalNotifications } from '@capacitor/local-notifications';


@Injectable({

  providedIn: 'root'

})


export class NotificationService {


  constructor() {

    this.checkPermission();

  }


  checkPermission() {

    return LocalNotifications.checkPermissions().then((res) => {

       if (res && res.display && res.display == 'denied') {

         LocalNotifications.requestPermissions().then((res) => {

           if (res && res.display && res.display == 'denied') {

             this.alert.presentToast("Need a Notification Permission to Set Reminder.");

           }

         })

       }

     });

  }


  async scheduleNotification(id: number, title: string, dateTime: any, description: string) {

    await LocalNotifications.schedule({

      notifications: [{

        id: id,

        title: title,

        body: description,

        schedule: {

          at: new Date(new Date(dateTime).getTime())

        },

        sound: 'notification.wav'

      }]

    });

  }

 

Add above file into the service folder and Inject into the component and call scheduleNotification function with proper parameters.


If you have any queries, reach me with a comment.

 

0 Comments:

Post a Comment