更新
我需要找到下一个通知请求和相关ID,所以我最终选择了这个:
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))
}
我认为这种方法可能提供更优雅的解决方案,但正如Duncan在下面指出的那样UNNotificationRequests无法比较:
requests.min(by: (UNNotificationRequest, UNNotificationRequest) throws -> Bool>)
如果有人有更好的解决方案,请告诉我。
答案 0 :(得分:1)
我认为Sequence
对符合min()
协议的对象序列有Comparable
函数。我认为UNNotificationRequest
个对象不具有可比性,因此您无法直接在min()
个对象数组上使用UNNotificationRequest
。
您必须先使用flatMap将通知数组转换为非零触发日期数组:
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)
}
(该代码可能需要稍微调整才能使其编译,但这是基本的想法。)