Swift中如何仅在工作日8:00-17:00按间隔调度本地通知
解决方案:限制本地通知仅在工作日推送
你当前的代码已经实现了固定间隔的重复通知,但缺少工作日的限制。只需在DateComponents中添加工作日的星期值,并为每个工作日单独创建通知请求即可实现需求,具体修改如下:
修改后的完整代码
func scheduleNotifications(timeInterval: Int) { let notificationCenter = UNUserNotificationCenter.current() notificationCenter.removeAllDeliveredNotifications() notificationCenter.removeAllPendingNotificationRequests() let startHour = 8 let totalHours = 9 // 8:00 到 17:00 共9小时 let totalIntervals = totalHours * (60 / timeInterval) // iOS中weekday取值:1=周日,2=周一,3=周二,4=周三,5=周四,6=周五,7=周六 let weekdays = [2, 3, 4, 5, 6] // 周一至周五 for weekday in weekdays { for i in 0..<totalIntervals { var date = DateComponents() date.weekday = weekday // 指定工作日 date.hour = startHour + (i * timeInterval) / 60 date.minute = (i * timeInterval) % 60 print("\(date.hour!):\(date.minute!) (周\(weekday-1))") let notification = UNMutableNotificationContent() notification.title = "App" notification.body = "Notification message" notification.categoryIdentifier = "reminder" notification.sound = .default let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true) let uuidString = UUID().uuidString let request = UNNotificationRequest(identifier: uuidString, content: notification, trigger: trigger) notificationCenter.add(request, withCompletionHandler: nil) } } } self?.scheduleNotifications(timeInterval: 30)
关键修改说明
- 添加工作日限制:通过
date.weekday = weekday指定通知触发的星期几,iOS中weekday的取值规则为1=周日、2=周一至6=周五;循环遍历周一至周五的weekday值,为每个时间点在不同工作日创建独立的重复通知。 - 修正时间起始点:将原代码中
i的循环范围从1...totalHalfHours改为0..<totalIntervals,确保第一个通知从8:00开始(而非原代码的8:30),完整覆盖8:00-16:30的区间。 - 适配任意时间间隔:用
(i * timeInterval) / 60计算小时数、(i * timeInterval) % 60计算分钟数,适配15分钟、60分钟等任意合法的时间间隔参数。
内容的提问来源于stack exchange,提问作者Ramdhas
相关产品推荐
相关产品推荐

