Capacitor / Ionic / Vue Local Notification eventlistener - vue.js

I'm trying to get Local Notifications working in an Ionic Vue app (using capacitor).
I did get scheduling notifications working, but now i want to listen to clicks on the notification.
in main.js I bind LocalNotifications to this.$LocalNotifications:
import { Plugins } from '#capacitor/core';
const { LocalNotifications } = Plugins;
Vue.prototype.$LocalNotifications = LocalNotifications;
in my Root component App I have this:
created() {
console.log('Created!')
document.addEventListener('deviceready', () => {
console.log('ready');
this.$LocalNotifications.addListener('localNotificationReceived', (notification) => {
console.log('Notification action received', notification);
});
}, false);
}
When I build and run on the ios-emulator, i get the following output in my log:
APP ACTIVE
To Native Cordova -> Badge load Badge1248600129 ["options": []]
⚡️ [log] - onscript loading complete
To Native Cordova -> Device getDeviceInfo Device1248600130 ["options": []]
⚡️ To Native -> Storage get 90127150
⚡️ TO JS {"value":null}
⚡️ [log] - Created!
To Native Cordova -> LocalNotification launch LocalNotification1248600131 ["options": []]
To Native Cordova -> LocalNotification ready INVALID ["options": []]
⚡️ To Native -> LocalNotifications addListener ⚡️ [log] - ready
90127151
⚡️ WebView loaded
⚡️ To Native -> App addListener 90127152
When I schedule a Notification, the notification does show up, but I think something doesn't go quite well when i'm adding the listener:
INVALID ["options":[]]
Does anyone have any idea how to solve this?
Or does anyone have a code example of working notifications in an Ionic Vue app?
Kind regards,
Bram

To sum up:
You should use localNotificationActionPerformed instead of localNotificationReceived. The latter is called when notifications are displayed, while the other is listening to actions performed on a notification (as it's stated in the docs), that of course includes clicking / tapping on it.
So your code would look like this:
this.$LocalNotifications.addListener('localNotificationActionPerformed', (notification) => {
console.log('Notification action received', notification.actionId);
});
...which would output "tap". Since you did write 'Notification action received', I assume you wanted to get the action, so I added .actionId after 'notification', which only by itself would be logged as [object Object] or as the object tree.
You also asked for code example, so here it comes:
// 1.
import { LocalNotifications } from '#capacitor/local-notifications';
// 2.
await LocalNotifications.requestPermissions();
// 3.
await LocalNotifications.registerActionTypes({
types: [
{
id: 'your_choice',
actions: [
{
id: 'dismiss',
title: 'Dismiss',
destructive: true
},
{
id: 'open',
title: 'Open app'
},
{
id: 'respond',
title: 'Respond',
input: true
}
]
}
]
});
// 4.
LocalNotifications.schedule({
notifications: [
{
id: 1,
title: 'Sample title',
body: 'Sample body',
actionTypeId: 'your_choice'
}
]
});
// 5.
LocalNotifications.addListener('localNotificationActionPerformed', (notification) => {
console.log(`Notification ${notification.notification.title} was ${notification.actionId}ed.`);
});
1: Since your question, plugins have been placed into their own npm packages, so one needs to install #capacitor/local-notifications and import from there.
2: You should make sure that notifications are allowed, ask for permissions if needed.
3: Tapping was your question's topic, but you can define a lot more than that.
4: This is how you actually create & send a notification at once.
5: Logs "Notification Sample title was taped / opened / dismissed / responded.", according to the given action (but not always according to grammar).
Finally, if someone's just getting into local notifications, check out the really nice documentation on what else (a whole lot more!) can be done and also watching this video might give one a head start. At least that's what I did.

Related

Message format for deeplink with react-native-push-notification

I am using react-native-push-notification library to send local notifications from my ios app. I have setup deeplink using react navigation. I have also managed the local push notification to deeplink into specific app screen on click. But this requires me to set the in the message property. This means the resulting lo shows the URL in its display. This is ugly and I would like to hide the URL. Any pointers?
Here is how i schedule local notification
PushNotification.localNotificationSchedule({
title: "main title",
subtitle: "fake sub title",
message: "example://detail/one",
bigText: "My big text that will be shown when expanded",
date: new Date(Date.now() + 10 * 1000),
allowWhileIdle: false,
});
Here is my onNotification code
onNotification: function (notification) {
console.log("NOTIFICATION:", notification);
let isClicked = notification.data.userInteraction === 1
if (isClicked) {
Linking.openURL(notification.message)
}
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
Now this results in the example://detail/one url being displayed in notification. How do i achieve this?
Not exactly a solution to the above issue. But I switched to Notifee for local push notifications. And it just worked! So much easier to install and very minimal configuration needed. Was just an intuitive I expected the notification library to be.

How to send session info and do automated page tracking in expo react native segment and amplitude integration

I am using Segment[expo-analytics-segment] to send tracking info to Amplitude(Configured as the destination in app.segment.com) in an expo react native app. Though I am sending session info(epoch time) - The session always gets registered as -1, hence I am unable to access 'funnel' feature in Amplitude.
Also - How do we enable automatic page tracking in expo segment+amplitude configuration?
This is what I have done so far in App.tsx
Segment.initialize({
androidWriteKey: 'androidKey', // from Segment
iosWriteKey: 'iOsKey', // from segment
});
global.epochInMilliSeconds = Date.now();
Segment.identifyWithTraits(
user.sub,
{ email: 'notgood#gmail.com' },
{
event: 'App Started',
integrations: {
Amplitude: {
sessionId: global.epochInMilliSeconds,
},
},
}
);
Segment.trackWithProperties(
'App Started',
{ email: 'fancyemail#gmail.com' },
{ integrations: { Amplitude: { session_id: global.epochInMilliSeconds } } }
); <------------------- Did not work. Session id is -1**
Segment.track('App Started'); // <-----------------------Session id is -1
More info - https://github.com/expo/expo/issues/10559
I followed this example for the above code sample: https://community.amplitude.com/instrumentation-and-data-management-57/how-do-we-set-session-in-amplitude-while-using-segment-in-cloud-mode-111
Amplitude website mentions that session Ids are not automatically tracked.
https://help.amplitude.com/hc/en-us/articles/217934128-Segment-Amplitude-Integration
In case the link changes, it says:
6. Why do all of my events have a sessionId of -1?
You need to use Segment's client-side bundled integration to have our native SDKs track Session IDs for you.

Scheduled Push Notification action onClick/onPress event in react native push notification?

I'm using this package for implementing local push notification:
https://github.com/zo0r/react-native-push-notification
I'm using action button like this to show buttons in my notification along with a text and a title:
PushNotification.localNotification({
...
actions: '["Yes", "No"]'
})
I wanted to know how I can call a function when user clicks on of these actions and app becomes visible?
I've tried PushNotification.configure in my componentDidMount method in my home screen like this but nothing comes up in the console:
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log("NOTIFICATION:", notification);
if (notification.userInteraction) {
console.log("NOTIFICATION:");
}
// process the notification
}
});
I got it working.
In your App.js you need to set popInitialNotification to true. Something like this:
async componentDidMount() {
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log("NOTIFICATION:", notification.action);
},
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true
},
// Should the initial notification be popped automatically
// default: true
popInitialNotification: true,
/**
* (optional) default: true
* - Specified if permissions (ios) and token (android and ios) will requested or not,
* - if not, you must call PushNotificationsHandler.requestPermissions() later
*/
requestPermissions: true
});
}
notification.action will gibe you the label of the button clicked.
In your button/app active event you forgot to call to schedule the notification and actually set when it will arise, so you need to
PushNotification.localNotificationSchedule(details: Object)
Schedule it for now with the same id, then your notification will come up immediately.
See all options for scheduling here
import PushNotificationAndroid from 'react-native-push-notification'
(function() {
// Register all the valid actions for notifications here and add the action handler for each action
PushNotificationAndroid.registerNotificationActions(['Accept','Reject','Yes','No']);
DeviceEventEmitter.addListener('notificationActionReceived', function(action){
console.log ('Notification action received: ' + action);
const info = JSON.parse(action.dataJSON);
if (info.action == 'Accept') {
// Do work pertaining to Accept action here
} else if (info.action == 'Reject') {
// Do work pertaining to Reject action here
}
// Add all the required actions handlers
});
})();
DO NOT USE .configure() INSIDE A COMPONENT, EVEN App
If you do, notification handlers will not fire, because they are not loaded. Instead, use .configure() in the app's first file, usually index.js.
It's mentioned in the documentation.
Try to follow their example for implementation It will help you to setup in your project.

React native local notifications

I am new to React Native and need to implement a functionality where the app needs to send the user a notification every day at a certain time. The data to be shown for each day is stored in a json file on the client side and will not change. The notifications are on a schedule. Given that I was hoping there could be a way to just trigger a notification from the app itself.
Does anyone know of a way to achieve this without having to detach the app from expo? I can't use 'react-native-push-notification'without running react-native link and that requires me to detach the app. Is that right?
Is this possible?
Thanks :)
You can do this with expo using the scheduleLocalNotificationAsync function (have a look at these docs for more details). Make sure you have permission to send notifications first. Note that if the notification triggers when the app is in the foreground you won't see a notification but you can still listen to this event.
i. Ask for permission
import { Permissions } from 'expo';
// ... somewhere before scheduling notifications ...
const { status } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
if (status !== 'granted') {
await Permissions.askAsync(Permissions.NOTIFICATIONS);
}
ii. Schedule the notification
import { Notifications } from 'expo';
const notification = {
title: 'Hi there!',
body: 'Tap me to open the app.',
android: { sound: true }, // Make a sound on Android
ios: { sound: true }, // Make a sound on iOS
};
const options = {
time: Date.now() + 10000, // Schedule it in 10 seconds
repeat: 'day', // Repeat it daily
};
// ... somewhere after requesting permission ...
const id = Notifications.scheduleLocalNotificationAsync(notification, options)
// If you want to react even when your app is still in the
// foreground, you can listen to the event like this:
Notifications.addListener(() => {
console.log('triggered!');
});
iii. Cancel the scheduled notification
You can use the returned id of the scheduleLocalNotificationAsync function to cancel the notification.
import { Notifications } from 'expo';
// ... get the id of the scheduled notification ...
Notifications.cancelScheduledNotificationAsync(id)

react native push notification that can be removed after button click

I am using react native v0.45.1.
How can I add to my application notification (no matter if the app is in the background or foreground) that the user can remove only after click an acknowledge button.
I don't want the user to swipe the notification aside without notice it.
how can it be done?
I am not sure https://github.com/wix/react-native-notifications will do what I need.
Edit
I want to have a notification that will act like:
'USB debugging connected
'Touch to disable USB debugging'
The notification can't be removed unless the user actively do something, in my case it will be 'click' on a button
after a lot of digging the solution I implemented was:
setting repeat interval for the notification.
for android:
repeatType: 'time',
repeatTime: timeSpan,
for iOS:
repeatType: 'minute',
when the user click the notification (decided its not the right approached to add actions - buttons - to notification):
PushNotification.configure({
onNotification: (notification) => {
console.log('NOTIFICATION:', notification);
const clicked = notification.userInteraction;
if (clicked) {
if (Platform.OS === 'ios') {
PushNotification.cancelLocalNotifications({ id: notification.data.id });
} else {
PushNotification.cancelLocalNotifications({ id: notification.id });
}
}
},
});
I am aware that this might not be the exact answer to this question. However,
I was looking for a similar solution earlier; how to remove notifications that hasn't been dismissed or opened by a user.
Sometimes the user might open the application / screen, without clicking on the notification. The notification will still be displayed in that case.
Using React Native with Expo, this is the solution I created for removing old notifications created using their Push Notification API.
import * as Notifications from "expo-notifications";
//...
// Remove notifications that exists for this conversation!
useEffect(() => {
Notifications.getPresentedNotificationsAsync().then(res => {
for (let k in res) {
if (
res[k].request.content.data &&
res[k].request.content.data.screen === "Conversations" &&
res[k].request.content.data.conversationId === conversationId
) {
Notifications.dismissNotificationAsync(res[k].request.identifier);
console.log("removed a notification for this conversation");
}
}
});
}, []);
By using the data sent to the Push Notification API, we can determine which notifications should be removed. in this case all notifications containing a conversationId matching the current value from the route are dismissed.