Update:
I needed to find the next notification request and the associated ID so I ended up going with this:
UNUserNotificationCenter.current().getPendingNotificationRequests {
(requests) in
var requestDates = [String:Date]()
for request in requests{
let requestId = request.identifier
let trigger = request.trigger as! UNCalendarNotificationTrigger
let triggerDate = trigger.nextTriggerDate()
requestDates[requestId] = triggerDate
}
let nextRequest = requestDates.min{ a, b in a.value < b.value }
print(String(describing: nextRequest))
}
I thought that this method might provide a more elegant solution but as Duncan pointed out below UNNotificationRequests are not comparable:
requests.min(by: (UNNotificationRequest, UNNotificationRequest) throws -> Bool>)
If anyone has a better solution then let me know.
I think that Sequence
has a min()
function for sequences of objects that conform to the Comparable
protocol. I don't think UNNotificationRequest
objects are comparable, so you can't use min()
on an array of UNNotificationRequest
objects directly.
You'd have to first use flatMap to convert your array of notifications to an array of non-nil trigger Dates:
UNUserNotificationCenter.current().getPendingNotificationRequests { requests in
//map the array of `UNNotificationRequest`s to their
//trigger Dates and discard any that don't have a trigger date
guard let firstTriggerDate = (requests.flatMap {
$0.trigger as? UNCalendarNotificationTrigger
.nextTriggerDate()
}).min() else { return }
print(firstTriggerDate)
}
(That code might need a little adjustment to make it compile, but it's the basic idea.)