1

更新:

我需要找到下一个通知请求和相关的 ID,所以我最终选择了这个:

    UNUserNotificationCenter.current().getPendingNotificationRequests {
        (requests) in
        var requestDates = [String:Date]()
        for request in requests{
            let requestId = request.identifier
            let trigger = request.trigger as! UNCalendarNotificationTrigger
            let triggerDate = trigger.nextTriggerDate()
            requestDates[requestId] = triggerDate
        }

        let nextRequest = requestDates.min{ a, b in a.value < b.value }
        print(String(describing: nextRequest))

        }

我认为这种方法可能会提供更优雅的解决方案,但正如 Duncan 在下面指出的 UNNotificationRequests 不可比:

requests.min(by: (UNNotificationRequest, UNNotificationRequest) throws -> Bool>)

如果有人有更好的解决方案,请告诉我。

4

1 回答 1

1

我认为它Sequence具有min()符合Comparable协议的对象序列的功能。我不认为UNNotificationRequest对象具有可比性,因此您不能直接在对象min()数组上使用UNNotificationRequest

您必须首先使用 flatMap 将通知数组转换为非零触发日期数组:

UNUserNotificationCenter.current().getPendingNotificationRequests { requests in
    //map the array of `UNNotificationRequest`s to their 
    //trigger Dates and discard any that don't have a trigger date
    guard let firstTriggerDate = (requests.flatMap { 
       $0.trigger as? UNCalendarNotificationTrigger
       .nextTriggerDate()
    }).min() else { return } 
    print(firstTriggerDate)
}

(该代码可能需要稍作调整才能使其编译,但这是基本思想。)

于 2018-04-05T18:27:19.323 回答