Local Notifications
@nativescript/local-notifications
The Local Notifications plugin allows your app to show notifications when the app is not running. Just like remote push notifications, but a few orders of magnitude easier to set up.
Installation
From the command prompt go to your app’s root folder and execute:
NativeScript 7+:
npm install @nativescript/local-notifications
NativeScript prior to 7:
tnpm install nativescript-local-notifications@4.2.1
Setup
Since plugin version 3.0.0
Add this so for iOS 10+ we can do some wiring (set the iOS UNUserNotificationCenter.delegate
, to be precise).
Not needed if your app loads the plugin on startup anyway.
You’ll know you need this if on iOS 10+ notifications are not received by your app or addOnMessageReceivedCallback
is not invoked…
better safe than sorry, though!
// either
import { LocalNotifications } from '@nativescript/local-notifications'
// or (if that doesn't work for you)
import * as LocalNotifications from '@nativescript/local-notifications'
// then use it as:
LocalNotifications.hasPermission()
Since plugin version 6.0.0
Both iOS and Android have to register their delegates and lifecycle callbacks, respectively.
Hence, if your app does not load this plugin at startup you will have to add the following to your app’s app.ts
/main.ts
file:
import '@nativescript/local-notifications'
// ... Bootstrap application
Plugin API
schedule
On iOS you need to ask permission to schedule a notification.
You can have the schedule
function do that for you automatically (the notification will be scheduled in case the user granted permission), or you can manually invoke requestPermission
if that’s your thing.
You can pass several options for this function. Everything is optional:
option | description |
---|---|
|
A number so you can easily distinguish your notifications. Will be generated if not set. |
|
The title which is shown in the statusbar. Default not set. |
|
Shown below the title on iOS, and next to the App name on Android. Default not set. All Android and iOS >= 10 only. |
|
The text below the title.
If not provided, the subtitle or title (in this order or priority) will be swapped for it on iOS, as iOS won’t display notifications without a body.
Default not set on Android, |
|
Custom color for the notification icon and title that will be applied when the notification center is expanded. (Android Only) |
|
Allow more than 1 line of the body text to show in the notification centre.
Mutually exclusive with |
|
An array of at most 5 messages that would be displayed using android’s notification inboxStyle. Note: The array would be trimmed from the top if the messages exceed five. Default not set |
|
An inboxStyle notification summary. Default empty |
|
On Android you can show a different text in the statusbar, instead of the |
|
A JavaScript Date object indicates when the notification should be shown. Default not set (the notification will be shown immediately). |
|
On iOS (and some Android devices) you see a number on top of the app icon. On most Android devices you’ll see this number in the notification center. Default not set (0). |
|
Notification sound.
For custom notification sound, copy the file to |
|
Set to one of |
|
On Android you can set a custom icon in the system tray.
Pass in |
|
Same as |
|
URL ( |
|
Custom thumbnail/icon to show in the notification center (to the right) on Android, this can be either: |
|
Default is ( |
|
Default is ( |
|
Default is |
|
Default is |
|
Add an array of |
|
Enable the notification LED light on Android (if supported by the device), this can be either: |
NotificationAction
option | description |
---|---|
|
An id so you can easily distinguish your actions. |
|
Either |
|
The label for |
|
Launch the app when the action completes. This will only work in apps targeting Android 11 or lower (target SDK < 31). |
|
The submit button label for |
|
The placeholder text for |
LocalNotifications.schedule([
{
id: 1, // generated id if not set
title: 'The title',
body: 'Recurs every minute until cancelled',
ticker: 'The ticker',
color: new Color('red'),
badge: 1,
groupedMessages: ['The first', 'Second', 'Keep going', 'one more..', 'OK Stop'], //android only
groupSummary: 'Summary of the grouped messages above', //android only
ongoing: true, // makes the notification ongoing (Android only)
icon: 'res://heart',
image: 'https://cdn-images-1.medium.com/max/1200/1*c3cQvYJrVezv_Az0CoDcbA.jpeg',
thumbnail: true,
interval: 'minute',
channel: 'My Channel', // default: 'Channel'
sound: isAndroid ? 'customsound' : 'customsound.wav',
at: new Date(new Date().getTime() + 10 * 1000) // 10 seconds from now
}
]).then(
scheduledIds => {
console.log('Notification id(s) scheduled: ' + JSON.stringify(scheduledIds))
},
error => {
console.log('scheduling error: ' + error)
}
)
Notification icons (Android)
These options default to res://ic_stat_notify
and res://ic_stat_notify_silhouette
respectively, or the app icon if not present.
silhouetteIcon
should be an alpha-only image and will be used in Android >= Lollipop (21).
These are the official icon size guidelines, and here’s a great guide on how to easily create these icons on Android.
Density qualifier | px | dpi |
---|---|---|
ldpi |
18 × 18 |
120 |
mdpi |
24 × 24 |
160 |
hdpi |
36 × 36 |
240 |
xhdpi |
48 × 48 |
320 |
xxhdpi |
72 × 72 |
480 |
xxxhdpi |
96 × 96 |
640 approx. |
Source: Density Qualifier Docs
addOnMessageReceivedCallback
Tapping a notification in the notification center will launch your app. But what if you scheduled two notifications and you want to know which one the user tapped?
Use this function to have a callback invoked when a notification was used to launch your app. Note that on iOS it will even be triggered when your app is in the foreground and a notification is received.
LocalNotifications.addOnMessageReceivedCallback(notification => {
console.log('ID: ' + notification.id)
console.log('Title: ' + notification.title)
console.log('Body: ' + notification.body)
}).then(() => {
console.log('Listener added')
})
getScheduledIds
If you want to know the ID’s of all notifications which have been scheduled, do this:
LocalNotifications.getScheduledIds().then(ids => {
console.log("ID's: " + ids)
})
cancel
If you want to cancel a previously scheduled notification (and you know its ID), you can cancel it:
LocalNotifications.cancel(5 /* the ID */).then(foundAndCanceled => {
if (foundAndCanceled) {
console.log("OK, it's gone!")
} else {
console.log('No ID 5 was scheduled')
}
})
cancelAll
If you just want to cancel all previously scheduled notifications, do this:
LocalNotifications.cancelAll()
requestPermission
On Android you don’t need permission, but on iOS you do. Android will simply return true.
If the requestPermission
or schedule
function previously ran the user has already been prompted to grant permission.
If the user granted permission this function returns true
, but if he denied permission this function will return false
, since an iOS can only request permission once.
In which case, the user needs to go to the iOS settings app and manually enable permissions for your app.
LocalNotifications.requestPermission().then(granted => {
console.log('Permission granted? ' + granted)
})
hasPermission
On Android you don’t need permission, but on iOS you do. Android will simply return true.
If the requestPermission
or schedule
functions previously ran you may want to check whether the user granted permission:
LocalNotifications.hasPermission().then(granted => {
console.log('Permission granted? ' + granted)
})