如何按 nextTriggerDate 对 UNNotificationRequests 数组进行排序
How to sort an array of UNNotificationRequests by nextTriggerDate
我有一个 UNNotificationRequest
的数组。我想按 nextTriggerDate
.
对它们进行排序
据我了解,我会使用 array.sorted(by:predicate)
对数组进行排序
let sortedNotifications = notificationRequests.sorted(by:
{ [=13=].trigger.nextTriggerDate?.compare(.trigger.nextTriggerDate!) == .orderedAscending })
但是,问题是 .trigger
没有 nextTriggerDate
属性。
为了获得nextTriggerDate
,我必须提取触发器并将其投射到UNCalendarNotificationTrigger
中。据我所知,不能在谓词中完成。
有什么想法吗?
您可以使用 UNNotificationRequest 和 nextTriggerDate (UNNotificationRequest,nextTriggerDate)
创建 Tuple
// 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({[=10=]})
// you will get Tuple (request,Date) ,sort them by date
let sortedTuple = requestWithDateTuple.sorted(by: { [=10=].1?.compare(.1!) == .orderedAscending })
// sorted request only
let requestSorted = sortedTuple.map({[=10=].0})
我有一个 UNNotificationRequest
的数组。我想按 nextTriggerDate
.
据我了解,我会使用 array.sorted(by:predicate)
let sortedNotifications = notificationRequests.sorted(by:
{ [=13=].trigger.nextTriggerDate?.compare(.trigger.nextTriggerDate!) == .orderedAscending })
但是,问题是 .trigger
没有 nextTriggerDate
属性。
为了获得nextTriggerDate
,我必须提取触发器并将其投射到UNCalendarNotificationTrigger
中。据我所知,不能在谓词中完成。
有什么想法吗?
您可以使用 UNNotificationRequest 和 nextTriggerDate (UNNotificationRequest,nextTriggerDate)
Tuple
// 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({[=10=]})
// you will get Tuple (request,Date) ,sort them by date
let sortedTuple = requestWithDateTuple.sorted(by: { [=10=].1?.compare(.1!) == .orderedAscending })
// sorted request only
let requestSorted = sortedTuple.map({[=10=].0})