为 UNNotificationRequest 检索下一个请求日期和关联的 ID
Retrieving next request date and associated ID for UNNotificationRequest
更新:
我需要找到下一个通知请求和关联的 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
对符合 Comparable
协议的对象序列有一个 min()
函数。我不认为 UNNotificationRequest
对象是可比较的,所以你不能直接在 UNNotificationRequest
对象的数组上使用 min()
。
您必须首先使用 flatMap 将通知数组转换为 non-nil 触发日期数组:
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 {
[=10=].trigger as? UNCalendarNotificationTrigger
.nextTriggerDate()
}).min() else { return }
print(firstTriggerDate)
}
(该代码可能需要稍作调整才能编译,但这是基本思想。)
更新:
我需要找到下一个通知请求和关联的 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
对符合 Comparable
协议的对象序列有一个 min()
函数。我不认为 UNNotificationRequest
对象是可比较的,所以你不能直接在 UNNotificationRequest
对象的数组上使用 min()
。
您必须首先使用 flatMap 将通知数组转换为 non-nil 触发日期数组:
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 {
[=10=].trigger as? UNCalendarNotificationTrigger
.nextTriggerDate()
}).min() else { return }
print(firstTriggerDate)
}
(该代码可能需要稍作调整才能编译,但这是基本思想。)