I'm having a problem with my local notification that is: if the device is in off state or when changing the date of phone, the notification is kept in queue and firing along with next notification. Why?
Since need to have very concern about the date of notification..
How to assure correct delivery of notification?
Where should we put code for removing expired notification?
So you mean you had a notification named ABC to be triggered in 30 minutes...but then you turned your iPhone off for 3 hours...then turned it on and saw that notification ABC notification even though its time was passed? AFAIK ....the notification will still be there unless you remove it using removeDeliveredNotifications(withIdentifiers:)
.
Basically call:
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["notificationIdentifer1", "notificationIdentifer2"]).
For more information see this moment of this WWDC video.
Also see this tutorial look for the section "4. Managing Notifications"
As to address your edit:
To be honest I'm not sure...but here's what I think you should do:
I suggest to make the class that creates the notifications:
Step1: Conform to UNUserNotificationCenterDelegate
Step2: Implement:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
}
Now that you turned your device on...This function would get called only if app is in background. There you have a chance to kill your obsolete notifications.
This function is called in both foreground and background, if it's background then you can kill obsolete notifications following step3, if it's foreground well then you don't need to do anything, it send off the queue itself, because it was shown!
Step3:
Inside the function you implemented do:
UNUserNotificationCenter.current().getDeliveredNotifications(completionHandler: {deliveredNotifications -> () in
print("\(deliveredNotifications.count) Delivered notifications-------")
for notification in deliveredNotifications{
if (someCondition){
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["notificationIdentifer1", "notificationIdentifer2"]).
}
}
})
As for the iPhone time change issue... you should come up with a reasonable condition and find the notification and remove it...or simply change your notification trigger from a UNCalendarNotificationTrigger
to UNTimeIntervalNotificationTrigger
. (though again I'm not sure if your timer resets itself or not. I think it shouldn't and you're good).