我有一个UNNotificationRequest
数组。我想按nextTriggerDate
对其进行排序。
据我了解,我将使用array.sorted(by:predicate)
对数组进行排序let sortedNotifications = notificationRequests.sorted(by:{ $0.trigger.nextTriggerDate?.compare($1.trigger.nextTriggerDate!) == .orderedAscending })
但是,问题是.trigger
没有nextTriggerDate
属性。
为了获得nextTriggerDate
,我必须提取触发器并将其转换为UNCalendarNotificationTrigger
。据我所知,这不能在谓词中完成。
有什么想法吗?
最佳答案
您可以使用UNNotificationRequest和nextTriggerDate Tuple
创建(UNNotificationRequest,nextTriggerDate)
// get request with date Tuple --> example : (value0,value1)
let requestWithDateTuple = notificationRequests.map({ (req) -> (UNNotificationRequest,Date?)? in
guard let trigger = req.trigger as? UNCalendarNotificationTrigger else {
return nil
}
return (req,trigger.nextTriggerDate())
}).compactMap({$0})
// you will get Tuple (request,Date) ,sort them by date
let sortedTuple = requestWithDateTuple.sorted(by: { $0.1?.compare($1.1!) == .orderedAscending })
// sorted request only
let requestSorted = sortedTuple.map({$0.0})