Local notifications don't work properly (tried it with ionic 3 & 4).
The user can set a time in the app and turn the notifications on or off.
When using the following code, I always get a notification at 01:00 am although I've set it to 17:30 or something else.
I tried many variations, this is the last one:
const time = setsub.task_reminder_time.split(':');
const now = new Date();
console.log('now is', now);
const pushDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), +time[0], +time[1], 0);
const options = {
id: 1,
title: 'Time to plan your day!',
text: `Hey you! It's time to get productive by planning your day!\nTap here to open DoDay! 🤓`,
trigger: { firstAt: pushDate, every: ELocalNotificationTriggerUnit.DAY }
};
if (setsub.task_reminder) {
this.notification.requestPermission();
this.notification.schedule(options);
} else {
this.notification.clearAll();
}
time is just a string containing the notification time in HH:mm
I'm using an iOS device for testing.
So I found the solution to this one by myself. It's an error in the typings file of LocalNotifications package.
The correct usage for the options look like this:
{
id: 1,
title: 'Notification Title',
text: 'Your notification text',
foreground: true,
trigger: {
every: {
hour: 8,
minute: 15
}
}
}
Just go into your node_modules/#ionic-native/local-notifications find the index.d.ts and find the line which says every?: ELocalNotificationTriggerUnit and change it to every?: any; now it should work perfectly.
Related
So, I have an app where users are reminded to take medicines every day at a particular time for a certain interval of dates. For example, the user can choose to get a notification from September 16,2020 to September 18,2020 at some time of the day
My approach : I schedule a notification using the flutter_local_notifications package with showDailyAtTime() function. However, the problem I face is that, suppose I don't open the app again, there is no way to cancel the scheduled notification and thus, the notification pops up even after the specified date range. I would like the notifications to be offline, so Firebase doesn't seem to be an option.
You can solve the problem with FlutterLocalNotificationsPlugin.
The approach would be to call the method rescheduleNotifications every time you start the app. In the method all notifications are removed and the next notifications are set. In calculateNotificationTimes for example you calculate all notifications for the next 30 days. For example, all notifications on September 16, 2020 to September 18, 2020 each day at a time of your choice.
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
Future<void> rescheduleNotifications() async {
final localNotificationsPlugin = FlutterLocalNotificationsPlugin();
const initializationSettings = InitializationSettings(AndroidInitializationSettings('app_icon'), IOSInitializationSettings());
const androidChannelSpecifics = AndroidNotificationDetails('your channel id', 'your channel name', 'your channel description');
const iOSNotificationDetails = IOSNotificationDetails();
const notificationsDetails = NotificationDetails(androidChannelSpecifics, iOSNotificationDetails);
await localNotificationsPlugin.initialize(initializationSettings);
await localNotificationsPlugin.cancelAll();
// Calculate the next notifications.
final notificationTimes = calculateNotificationTimes();
var _currentNotificationId = 0;
for (final time in notificationTimes) {
localNotificationsPlugin.schedule(
_currentNotificationId++,
"It's time to take your medicine.",
'Take the red pill',
time,
notificationsDetails,
androidAllowWhileIdle: true,
);
}
}
On iOS there is a limit that you can only have 64 notifications enabled. The disadvantage of this method on iOS is that if the user does not open the app after 64 notifications, no notification will be displayed. Which is fine, I think, because it seems that the user does not use the app anymore.
Did not test the code.
As related to this documentation :
https://capacitorjs.com/docs/apis/local-notifications
It seems possible to use Capacitor local notification plugin for the web as pwa also.
I try to push "test" a local notification every 10 seconds but nothing happen even with service worker enabled
import { Plugins } from '#capacitor/core';
const { LocalNotifications } = Plugins;
const notifs = await LocalNotifications.schedule({
notifications: [
{
title: "Title",
body: "Body",
id: 1,
schedule: {
repeats: true,
every: "second",
count: 10
},
sound: null,
attachments: null,
actionTypeId: "",
extra: null
}
]
});
console.log('scheduled notifications', notifs);
In the source code of the LocalNotification plugin for web it seems as though the notification is only scheduled if the schedule option has the "at" property.
Even then I can't get it to work on chrome for android.
Notification scheduling for PWAs is currently in trial using the TimestampTrigger so I think the lack of browser support is the issue. Possibly getting out of trial during 2021. Just have to wait and see I guess.
This has obviously been asked multiple times but I can't seem to get any of the proposed solutions working.
Push notifs work when tethered to xcode. Untethered, I get the push notification itself but none of the delegate methods are called which results in not being able to increment badge count.
I also can't get silent notifications working on untethered as well. I use silent notifications to clear a notification with a given condition.
I've tried allowing background mode in plist, changing priorities, having an empty body. I've made sure that the device background refresh is on and that notifs are fully on. I've tried a ton more things that I can't remember off the top of my head. Nothing seems to work. I added a badge increment in every one of the push notif delegate methods and it seems none of them get called.
Here is the .js code snippet for regular notif
message1 = {
notification: {
title: "stackOverFlowTitle",
body: "stackOverFlowBody"
},
apns: {
payload: {
aps : {
"content-available": 1,
"sound": "default",
"priority" : 10
},
data: {
// collection: 'TestCollection',
// document: change.after.ref.id,
timePushed: timePushed,
alertOn: alertOn,
readNotification: readNotification,
eventKey: eventKey
}
},
headers: {
"apns-expiration": "4"
}
},
topic: topic
};
Here is the .js code snippet for silent notif
var message2 = {
notification: {
body: ""
},
apns: {
payload: {
aps: {
"content-available": 1,
"priority" : 10
},
data: {
alertOn: alertOn,
eventKey: eventKey
}
},
headers: {
"apns-expiration": "4"
}
},
topic: topic
};
Anyone have any potential solutions I haven't mentioned?
I changed silent notif priority to 5 and that helped (for this post) :D
According to the docs, when non-zero the apns-expiration represents a unix timestamp. By setting it to 4, you're telling APNs to expire the notification at 1970-01-01 00:00:04.
Does someone have experience with ionic 1 push notifications? Is there any alternative to cloud solution that they suggest? And can someone show example of implementatio? And please have on mind that I'm completly new in ionic
I use this plugin https://github.com/phonegap/phonegap-plugin-push to handle push notification.
var pushOptions = {
android: {
senderID: "1234567890",
icon: "push_icon",
iconColor: "#FFF"
},
ios: {
alert: true,
badge: true,
sound: true
}
};
var push = PushNotification.init(pushOptions);
push.on('registration', function () {});
push.on('notification', function () {});
After test several push servicies (ionic push service, parse, pushwoosh and one signal) we choose one signal as push notification provider. Right now we use it in 30+ production applications in our company. In 10 minutes or less you can set up an app for first push notification use in android or iOS (platforms we are working right now)
The platform has an easy set up guide.
The only code in app for basic setup is:
$ionicPlatform.ready(function() {
// Enable to debug issues.
// window.plugins.OneSignal.setLogLevel({logLevel: 4, visualLevel: 4});
var notificationOpenedCallback = function(jsonData) {
console.log('notificationOpenedCallback: ' + JSON.stringify(jsonData));
};
window.plugins.OneSignal
.startInit("YOUR_APPID")
.handleNotificationOpened(notificationOpenedCallback)
.endInit();
// Call syncHashedEmail anywhere in your app if you have the user's email.
// This improves the effectiveness of OneSignal's "best-time" notification scheduling feature.
// window.plugins.OneSignal.syncHashedEmail(userEmail);
})
Just modify "YOUR_APPID" by yours and thats all.
Follow de docs above for make it works in your desired platform.
Check out OneSignal. It's free, easy to use and multi-platform Push Notification framework.
I am trying to implement local noti operation on my mobile app. I can successfully schedule the notification but cannot get the "trigger event".
constructor(public platform:Platform, public nav:NavController, public navParams:NavParams,
public builder:FormBuilder, public menu:MenuController, public verify:VerifyToken) {
// after local noti alert trigger, badge number increases 1
LocalNotifications.on("trigger", (notification, state) => {
this.nav.present(alert);
// badge number increase 1.
Badge.increase(1);
});
// local push for alarming 30mins before reservation
LocalNotifications.on("click", (notification, state) => {
// badge number 0
Badge.clear();
let alert = Alert.create({
title: "scheduled!",
subTitle: "scheduled!",
buttons: ["OK"]
});
this.nav.present(alert);
});
}
scheduleAppointment() {
LocalNotifications.schedule({
title: "scheduled!,
text: "ready to go!",
at: moment(this.reservation.start).subtract(1800, 'seconds').toDate()
});
}
When it's the time, local notification works but cannot catch the trigger event so that badge count doesn't increase.. How can I solve this? thanks in advance!
Maybe you have to use
cordova.plugins.notification.local.on({ ... }) instead LocalNotifications.on.
Use it after platform is ready and it will be ok.