如何通过DateComponents设置多种重复通知触发规则?
嘿,我刚好之前在开发App时碰到过一模一样的需求!UNCalendarNotificationTrigger确实没办法一次性设置多个星期几,但我们可以通过创建多个触发器的方式轻松实现你要的各种重复规则,下面分场景给你具体方案:
1. 每日重复
这个是最简单的情况,只需要指定小时和分钟,不需要设置weekday,开启重复后每天这个时间都会触发通知:
var dateInfo = DateComponents() dateInfo.hour = 7 dateInfo.minute = 0 let dailyTrigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true)
2. 工作日重复(周一至周五)
iOS里weekday的取值是1(周日)、2(周一)……6(周五)、7(周六),所以我们可以遍历周一到周五的weekday值,给每个值创建一个独立的触发器和通知请求:
// 定义工作日的weekday数组:周一到周五 let workdays = [2, 3, 4, 5, 6] let targetHour = 7 let targetMinute = 0 for weekday in workdays { var dateInfo = DateComponents() dateInfo.hour = targetHour dateInfo.minute = targetMinute dateInfo.weekday = weekday // 创建触发器 let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true) // 创建唯一的通知请求ID,方便后续管理 let request = UNNotificationRequest( identifier: "workday_notification_\(weekday)", content: yourNotificationContent, // 这里替换成你的通知内容 trigger: trigger ) // 添加到通知中心 UNUserNotificationCenter.current().add(request) }
3. 周末重复(周六+周日)
和工作日逻辑一致,只需要把weekday数组换成周日(1)和周六(7)即可:
let weekends = [1, 7] // 周日、周六 let targetHour = 7 let targetMinute = 0 for weekday in weekends { var dateInfo = DateComponents() dateInfo.hour = targetHour dateInfo.minute = targetMinute dateInfo.weekday = weekday let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true) let request = UNNotificationRequest( identifier: "weekend_notification_\(weekday)", content: yourNotificationContent, trigger: trigger ) UNUserNotificationCenter.current().add(request) }
4. 每周指定几天重复
这其实是上面两种情况的通用版,你只需要把weekday数组换成自己需要的日期就行,比如指定周一、周三、周五:
// 自定义要重复的星期几:周一、周三、周五 let targetWeekdays = [2, 4, 6] let targetHour = 7 let targetMinute = 0 for weekday in targetWeekdays { var dateInfo = DateComponents() dateInfo.hour = targetHour dateInfo.minute = targetMinute dateInfo.weekday = weekday let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true) let request = UNNotificationRequest( identifier: "custom_weekday_notification_\(weekday)", content: yourNotificationContent, trigger: trigger ) UNUserNotificationCenter.current().add(request) }
几个注意点
- 每个通知请求的identifier必须唯一,这样后续你要修改或取消某个重复规则时,可以通过identifier精准找到对应的请求。
- 如果用户后续修改了重复规则,记得先移除之前添加的所有相关通知请求,再添加新的,避免出现重复通知的情况。比如可以用:
// 假设你之前保存了所有相关的identifier数组 let oldIdentifiers = ["workday_notification_2", "workday_notification_3", ...] UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: oldIdentifiers)
内容的提问来源于stack exchange,提问作者Jin




