2

So 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...

Hour: 16 Minute: 10 Second: 0, repeats: YES>

but i can't call trigger.dateComponents

How do I get this date?

c0nman
  • 189
  • 1
  • 12

4 Answers4

8

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()]
MAVO
  • 153
  • 1
  • 10
3

You need to cast UNNotificationTrigger to UICalendarNotificationTrigger and get its nextTriggerDate

if let calendarNotificationTrigger = notifications.first?.trigger as? UNCalendarNotificationTrigger, 
    let nextTriggerDate = calendarNotificationTrigger.nextTriggerDate()  {
    print(nextTriggerDate)  
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
1

You want to use dateComponents of the UNCalendarNotificationTrigger. try using notification.fireDate to retrieve that.

More info on Apple Developer Documentation: https://developer.apple.com/documentation/usernotifications/uncalendarnotificationtrigger

Anushk
  • 482
  • 4
  • 20
1

To get the next notification you need to get the dates for all the requests and select the lowest:

UNUserNotificationCenter.current().getPendingNotificationRequests {
    (requests) in
    var nextTriggerDates: [Date] = []
    for request in requests {
        if let trigger = request.trigger as? UNCalendarNotificationTrigger,
            let triggerDate = trigger.nextTriggerDate(){
            nextTriggerDates.append(triggerDate)
        }
    }
    if let nextTriggerDate = nextTriggerDates.min() {
        print(nextTriggerDate)
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Travis S.
  • 343
  • 1
  • 4
  • 14