如何通过nextTriggerDate对UNNotificationRequests数组进行排序

时间:2018-05-10 18:04:38

标签: ios sorting nspredicate unnotificationrequest unnotificationtrigger

我有一个UNNotificationRequest数组。我希望按nextTriggerDate排序。

据我了解,我会使用array.sorted(by:predicate)

对数组进行排序

let sortedNotifications = notificationRequests.sorted(by: { $0.trigger.nextTriggerDate?.compare($1.trigger.nextTriggerDate!) == .orderedAscending })

但问题是.trigger没有nextTriggerDate属性。

为了获得nextTriggerDate,我必须提取触发器并将其转换为UNCalendarNotificationTrigger。据我所知,这不能在谓词中完成。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用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})