I'm trying to schedule local notifications on only weekdays, between the 8am to 5pm. Need to trigger a local notification on given time interval.
func scheduleNotifications(timeInterval: Int) {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.removeAllDeliveredNotifications()
notificationCenter.removeAllPendingNotificationRequests()
let startHour = 8
let totalHours = 9
let totalHalfHours = totalHours * (60/timeInterval)
for i in 1...totalHalfHours {
var date = DateComponents()
date.hour = startHour + i / 2
date.minute = timeInterval * (i % 2)
print("\(date.hour!):\(date.minute!)")
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)
Using the above code, i'm able to schedule the notification on every 30 minutes. But, I face challenge in restrict this notifications only for the weekdays.
One solution would be to add an inner (or outer) loop from
2...6(Monday to Friday) and use that to set theweekdayproperty ofdate. This means you create 5 times as many notifications but it narrows each set to one day per week.Note that once you call
scheduleNotificationsonce, never call it again in the lifetime of the app being installed without first deleting all existing scheduled notifications. This is because each notification you are creating is not limited to any specific date. So if you callscheduleNotificationsmore than once without purging existing notifications, you now have two or more notifications schedule for each time slot.But now you have a bigger problem. I've seen a few references state that you can only schedule 64 notifications. But you need 18 per day, 5 days per week. That's 90. That's too many. You are going to need a different approach to avoid the limit.