3

我有一个数组UNNotificationRequest。我想对它们进行排序nextTriggerDate

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

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

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

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

有什么想法吗?

4

1 回答 1

3

您可以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})
于 2018-05-10T18:29:49.830 回答