glv19 glv19 - 17 days ago 6
iOS Question

Accessing the scheduled date of a UNNotificationRequest object

I'm try to find the scheduled fire date of a UNNotificationRequest object.

I'm fetching the pending notifications requests like this:

UNUserNotificationCenter.current().getPendingNotificationRequests { (notifications) in

let pendingNotifications : [UNNotificationRequest] = notifications
}


I'm then trying to access the fire date of each UNNotificationRequest object.

I can access the UNNotificationTrigger as below but can't find a way to access the scheduled fire date of the notification.

let notification = pendingNotifications[indexOfNotification]
let trigger : [UNNotificationTrigger] = notification.trigger


I've been able to access the date of some notifications as below:

let date = trigger.value(forKey: "date") as! Date


This works for notifications scheduled using UNUserNotificationCenter but I get the following error when trying to access the date of notifications scheduled before iOS 10.


Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ valueForUndefinedKey:]: this class is not key value coding-compliant for the key date.'


Is there a method that will support both the new and old notifications.

Thank you.

Answer

can't find a way to access the scheduled fire date of the notification.

You have already shown that you understand how to get the UNNotificationTrigger. Well, UNNotificationTrigger is an abstract superclass. You need to find out what class it really is and cast it down to that class. Then you can explore its properties.

For example:

  • If it is a UNCalendarNotificationTrigger, then cast it down to a UNCalendarNotificationTrigger. Now it has a nextTriggerDate.

  • If it is a UNTimeIntervalNotificationTrigger, then cast it down to a UNTimeIntervalNotificationTrigger. Now it has a nextTriggerDate.