When a user sets up a notification for an item, they are asked for a timeframe in which they wish the notifications to trigger. For example, they want a repeating notification every 2 hours between 8am-8pm.
I know that I can run a for loop and setup separate notifications for 8am, 10am, 12pm, and so on, but I'm hoping there's a better solution.
There are two main reasons for doing it this way:
- I won't hit the 64 local notification limit if I can setup a single notification that only triggers between the hours the user sets.
- I can use a single identifier instead of needing to create and store every custom identifier for all of the separate notifications.
Also, I am trying not to have to use push notifications due to a user needing to have an active internet connection in order to receive them.
Here's my current function to schedule a notification:
func scheduleNotification(ident: String, hour: Int, minute: Int) {
let content = UNMutableNotificationContent()
content.title = "This is a test Notification"
content.subtitle = "Just a test"
content.sound = .default
content.badge = NSNumber(value: UIApplication.shared.applicationIconBadgeNumber + 1)
// calendar
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(
identifier: ident,
content: content,
trigger: trigger
)
UNUserNotificationCenter.current().add(request) { error in
if (error != nil) {
print("Error: \(String(describing: error?.localizedDescription))")
} else {
print("Successfully Scheduled")
}
}
}
In a perfect world, instead of triggering via the UNCalendarNotificationTrigger and setting DateComponents(), I would instead do something like:
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: (120x60), timespanStartHour: 8, timespanStartMinute: 0, timespanEndHour: 20, timespanEndMinute: 0, repeats: true)
Of course I know that timespanX parameters are not a thing. I was just trying to show an example of what would be a perfect scenario for my use case.