Как отсортировать массив UNNotificationRequests по nextTriggerDate - PullRequest
0 голосов
/ 10 мая 2018

У меня есть массив 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 голосов
/ 10 мая 2018

Вы можете создать Tuple С помощью UNNotificationRequest и nextTriggerDate (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})
...