gpt4 book ai didi

swift - 为 UNNotificationRequest 检索下一个请求日期和关联的 ID

转载 作者:行者123 更新时间:2023-11-28 06:01:09 27 4
gpt4 key购买 nike

更新:

我需要找到下一个通知请求和关联的 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>)

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

最佳答案

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

您必须首先使用 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)
}

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

关于swift - 为 UNNotificationRequest 检索下一个请求日期和关联的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49676957/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com