I'm trying to schedule a series of notifications when the user first opens the app so I have the following code, but the problem is they get scheduled for 18:30 instead of 19:30. The strange thing is that if I schedule just one notification without the while loop, index 0 of the array works as 19:30, but the others don't. Any ideas what I'm doing wrong?
Also, if this is a really stupid way of doing this, please tell me. I do need the days to be specific (so 1, 3, 5, 7, 14... days from the current day). Thank you.
let triggerDates = [
// Notifications for the first week
Calendar.current.date(byAdding: .day, value: 1, to: Date())!,
Calendar.current.date(byAdding: .day, value: 3, to: Date())!,
Calendar.current.date(byAdding: .day, value: 5, to: Date())!,
Calendar.current.date(byAdding: .day, value: 7, to: Date())!,
// Notifications for the month
Calendar.current.date(byAdding: .day, value: 14, to: Date())!,
Calendar.current.date(byAdding: .day, value: 21, to: Date())!,
// Notifications afterward
Calendar.current.date(byAdding: .day, value: 42, to: Date())!,
Calendar.current.date(byAdding: .day, value: 84, to: Date())!]
var notificationToSchedule = 7
while notificationToSchedule >= 0 {
var dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: triggerDates[notificationToSchedule])
dateComponents.hour = 19
dateComponents.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: "notification\(notificationToSchedule)", content: content, trigger: trigger)
center.add(request)
print(trigger.nextTriggerDate() ?? "nil")
notificationToSchedule -= 1
}
This is what the console outputs with this code:
2019-06-21 18:30:00 +0000
2019-05-10 18:30:00 +0000
2019-04-19 18:30:00 +0000
2019-04-12 18:30:00 +0000
2019-04-05 18:30:00 +0000
2019-04-03 18:30:00 +0000
2019-04-01 18:30:00 +0000
2019-03-30 19:30:00 +0000