I’m trying to implement a feature in my iOS app where I need to schedule local notifications that repeat at different intervals “weekly“, “monthly“, or “yearly“, starting from a specified date. I’m using the UNCalendarNotificationTrigger with the repeats parameter set to true, but I’m not sure if it handles different repeating periods as expected.
Here’s the function I’ve written:
func scheduleNotifications(startDate: Date?, remindersDayBefore: Int16, periodType: PeriodType) {
// Calculate the reminder date based on the start date and reminders day before
let calendar = Calendar.current
var reminderDate = calendar.date(byAdding: .day, value: 0, to: startDate)!
let currentDate = Date()
// If the reminder date is in the past, calculate the next occurrence
if reminderDate < currentDate {
switch periodType {
case .weekly:
reminderDate = calendar.date(byAdding: .day, value: 0, to: reminderDate)!
case .monthly:
reminderDate = calendar.date(byAdding: .month, value: 0, to: reminderDate)!
case .yearly:
reminderDate = calendar.date(byAdding: .year, value: 0, to: reminderDate)!
return
}
}
// Extract date components for the trigger
var reminderComponents = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: reminderDate)
// Create the notification content
let content = UNMutableNotificationContent()
switch remindersDayBefore {
case 0:
content.title = "Reminder: Event today"
content.body = "This is a reminder that your event is today."
case 1:
content.title = "Reminder: Event tomorrow"
content.body = "This is a reminder that your event is tomorrow."
default:
content.title = "Reminder: Event in (remindersDayBefore) days"
content.body = "This is a reminder that your event is scheduled in (remindersDayBefore) days."
}
content.sound = .default
// Create the calendar notification trigger
let trigger = UNCalendarNotificationTrigger(dateMatching: reminderComponents, repeats: true)
// Create the notification request
let notificationRequest = UNNotificationRequest(identifier: subscription.id.uuidString, content: content, trigger: trigger)
// Add the notification request
UNUserNotificationCenter.current().add(notificationRequest) { (error) in
if let error = error {
print("Error adding notification: (error)")
} else {
print("Notification scheduled successfully.")
}
}
}
My Questions:
-
Will this setup correctly handle notifications that repeat weekly,
monthly, or yearly? Specifically, I’m concerned about the
UNCalendarNotificationTrigger and whether it will continue to work
correctly for these different intervals after the initial trigger. -
How can I test these notifications to make sure they work as
expected for future dates and different repeating periods? I’ve had
trouble testing on a real device and the iOS simulator is tied to
the macOS system date.
Thanks in advance!