如何在 swift 中获取即将到来的通知的日期?

How to get date of upcoming notification in swift?

所以我可以用下面的代码得到下一个通知:

let center = UNUserNotificationCenter.current()
    center.getPendingNotificationRequests { (notifications) in

        let pendingNotifications : [UNNotificationRequest] = notifications
        let notification = pendingNotifications[0]
        let trigger = notification.trigger
        let content = notification.content
    }

触发让我...

小时:16 分钟:10 第二个:0,重复:YES>

但是我不能打电话给 trigger.dateComponents

我如何获得这个日期?

您想使用 dateComponentsUNCalendarNotificationTrigger。尝试使用 notification.fireDate 检索它。

有关 Apple 开发者文档的更多信息:https://developer.apple.com/documentation/usernotifications/uncalendarnotificationtrigger

您需要将 UNNotificationTrigger 转换为 UICalendarNotificationTrigger 并获取其 nextTriggerDate

if let calendarNotificationTrigger = notifications.first?.trigger as? UNCalendarNotificationTrigger, 
    let nextTriggerDate = calendarNotificationTrigger.nextTriggerDate()  {
    print(nextTriggerDate)  
}

要获得下一个通知,您需要获取所有请求的日期,select 最低的日期:

UNUserNotificationCenter.current().getPendingNotificationRequests {
    (requests) in
    var nextTriggerDates: [Date] = []
    for request in requests {
        if let trigger = request.trigger as? UNCalendarNotificationTrigger,
            let triggerDate = trigger.nextTriggerDate(){
            nextTriggerDates.append(triggerDate)
        }
    }
    if let nextTriggerDate = nextTriggerDates.min() {
        print(nextTriggerDate)
    }
}

使用nextTriggerDate()时需要小心。它可能会提供您不期望的日期。

见下文Does UNTimeIntervalNotificationTrigger nextTriggerDate() give the wrong date?

我已经能够确认在使用时间间隔触发器时会发生这种情况,这也可能会影响日历触发器。

虽然 nextTriggerDate() 提供的日期可能不是您所期望的,但 OS 的时间表实际上是正确的。

在通知内容 (UNNotificationContent) 的 userInfo 属性 中附加一些日期相关数据可能会对您有所帮助。

let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "This is a test"
content.sound = UNNotificationSound.default()
content.userInfo = ["date" : Date()]