Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get date of upcoming notification?

I can get the next notification with the following code:

let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests { (notifications) in
    let pendingNotifications : [UNNotificationRequest] = notifications
    let notification = pendingNotifications[0]
    let trigger = notification.trigger
    let content = notification.content
}

trigger gets me:

<UNCalendarNotificationTrigger: 0x6000004319e0; dateComponents: <NSDateComponents: 0x60000014f570>
    Hour: 16
    Minute: 10
    Second: 0, repeats: YES>

But I can't call trigger.dateComponents

How do I get this date?

like image 877
c0nman Avatar asked Dec 21 '25 14:12

c0nman


2 Answers

You need to be careful when using nextTriggerDate(). It might be providing a date that you are not expecting.

See the follow Does UNTimeIntervalNotificationTrigger nextTriggerDate() give the wrong date?.

I've been able to confirm that this is happening when using a time interval trigger, this might be affect calendar triggers as well.

Though the date nextTriggerDate() provides might not be what you are expecting, the schedule by the OS is actually correct.

It might be helpful for you to attach some date related data in the userInfo property of the notification content (UNNotificationContent).

let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "This is a test"
content.sound = UNNotificationSound.default()
content.userInfo = ["date" : Date()]
like image 69
MAVO Avatar answered Dec 24 '25 04:12

MAVO


You need to cast UNNotificationTrigger to UNCalendarNotificationTrigger and get its nextTriggerDate.

if let calendarNotificationTrigger = notifications.first?.trigger as? UNCalendarNotificationTrigger, 
    let nextTriggerDate = calendarNotificationTrigger.nextTriggerDate() {
    print(nextTriggerDate)  
}
like image 24
Leo Dabus Avatar answered Dec 24 '25 04:12

Leo Dabus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!