CristianMoisei
CristianMoisei

Reputation: 2279

Swift: Local Notifications get scheduled 1h earlier

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

Upvotes: 0

Views: 85

Answers (1)

Upholder Of Truth
Upholder Of Truth

Reputation: 4721

This is related to daylight saving and because it is changing on the 31/03/2019. Also if you put a breakpoint and check the contents of the triggerDates array you will see what the dates actually look like and it is only the printing to the console that is causing your issue.

If you add 1 days in BST on the 30/03/2019 you are in fact only adding 23 hours in UTC because of daylight saving time. However if you convert it back it will be ok.

Upvotes: 2

Related Questions