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

Swift中如何读取本地通知触发器的DateComponents?

解决iOS本地通知按触发日期筛选清理的问题

核心逻辑

要实现按触发日期筛选并清理通知,关键是从通知触发器中提取具体日期,步骤如下:

  • 判断触发器类型:仅UNCalendarNotificationTrigger包含可解析的日期组件
  • 将NSDateComponents转换为Date对象(基于系统当前日历,避免时区偏差)
  • 计算触发日期与当前日期的间隔,筛选出符合条件的通知进行删除

具体实现代码

修改你的LocalNotificationManager类,新增筛选清理的函数:

class LocalNotificationManager {
    
    static let shared = LocalNotificationManager()
    let notificationCenter = UNUserNotificationCenter.current()
    
    // 原列出待发送通知函数
    func listScheduledNotifications() {
        notificationCenter.getPendingNotificationRequests { requests in
            for request in requests {
                print("Notification [\(request.identifier)], \(String(describing: request.trigger))")
            }
            print("Pending notifications: [\(requests.count)]")
        }
    }
    
    // 清理触发时间在2天及以后的待发送通知
    func cleanUpFutureNotifications() {
        notificationCenter.getPendingNotificationRequests { [weak self] requests in
            guard let self = self else { return }
            
            let calendar = Calendar.current
            let todayStart = calendar.startOfDay(for: Date())
            guard let twoDaysLater = calendar.date(byAdding: .day, value: 2, to: todayStart) else { return }
            
            var identifiersToDelete = [String]()
            
            for request in requests {
                // 仅处理日历类型触发器
                guard let calendarTrigger = request.trigger as? UNCalendarNotificationTrigger else {
                    continue
                }
                
                // 将日期组件转换为具体日期
                guard let triggerDate = calendar.date(from: calendarTrigger.dateComponents) else {
                    continue
                }
                
                let triggerDayStart = calendar.startOfDay(for: triggerDate)
                
                // 判断是否需要删除:触发日期在2天后及以后
                if triggerDayStart >= twoDaysLater {
                    identifiersToDelete.append(request.identifier)
                }
            }
            
            // 执行删除操作
            if !identifiersToDelete.isEmpty {
                self.notificationCenter.removePendingNotificationRequests(withIdentifiers: identifiersToDelete)
                print("Removed \(identifiersToDelete.count) future notifications")
            }
        }
    }
}

关键细节说明

  • 类型强转:必须将trigger转为UNCalendarNotificationTrigger,其他触发器类型(如UNTimeIntervalNotificationTrigger)不包含日期组件
  • 日期对齐:用startOfDay(for:)将日期统一到当日零点,避免小时、分钟的干扰,确保按自然日判断
  • 内存安全:闭包中使用[weak self]防止循环引用
  • 时区兼容:基于系统当前日历转换日期,避免时区差异导致的日期判断错误

内容的提问来源于stack exchange,提问作者zkvvoob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:52:21