You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取UNNotificationRequest的下一个触发日期及关联ID

获取下一个待处理UNNotificationRequest及其关联ID

如果要找出下一个即将触发的待处理通知请求,同时拿到它的关联ID,你可以用下面这段代码实现:

UNUserNotificationCenter.current().getPendingNotificationRequests { (requests) in
    var requestDates = [String: Date]()
    
    for request in requests {
        let requestId = request.identifier
        // 这里假设所有待处理通知都是日历触发器,若有其他类型触发器需要做类型判断
        if let trigger = request.trigger as? UNCalendarNotificationTrigger {
            let triggerDate = trigger.nextTriggerDate()
            requestDates[requestId] = triggerDate
        }
    }
    
    // 找出触发时间最早的通知请求
    let nextRequest = requestDates.min { a, b in
        a.value < b.value
    }
    
    // 这里可以处理nextRequest,比如取出ID和时间
    if let next = nextRequest {
        print("下一个通知ID:\(next.key),触发时间:\(next.value ?? Date())")
    }
}

代码逻辑拆解:

  • 先通过UNUserNotificationCenter.current()获取当前设备的通知中心实例
  • 调用getPendingNotificationRequests异步拉取所有处于待处理状态的通知请求
  • 创建字典requestDates,用来存储每个通知的唯一ID(作为键)和对应的下一次触发时间(作为值)
  • 遍历请求列表时,先提取通知的identifier,再尝试将触发器转为UNCalendarNotificationTrigger(如果你的项目里还有时间间隔触发器这类其他类型,一定要加类型判断避免崩溃)
  • 通过nextTriggerDate()拿到该通知的下一次触发时间,存入字典
  • 利用字典的min方法,根据触发时间的先后排序,筛选出时间最早的键值对,这就是下一个要触发的通知

额外提醒:

如果你的通知系统包含多种触发器类型,记得扩展类型判断逻辑,比如同时兼容UNTimeIntervalNotificationTrigger,保证代码在复杂场景下的健壮性。

内容的提问来源于stack exchange,提问作者Travis S.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:07:15