4

When I run the following (on January 7 2017):

        let dateComponents = Calendar.current.dateComponents(in: TimeZone.current, from: date)
        print("dateComponents = \(dateComponents)")
        let trigger = UNCalendarNotificationTrigger(dateMatching:dateComponents, repeats: false)
        let nextDate = trigger.nextTriggerDate()
        print("nextDate = \(nextDate)")

then I get the following output:

dateComponents = calendar: gregorian (current) timeZone: Europe/Stockholm (current) era: 1 year: 2017 month: 1 day: 8 hour: 21 minute: 34 second: 0 nanosecond: 0 weekday: 1 weekdayOrdinal: 2 quarter: 0 weekOfMonth: 1 weekOfYear: 1 yearForWeekOfYear: 2017 isLeapMonth: false

nextDate = nil

Question: why is trigger.nextTriggerDate() = nil ?

UPDATE: I had the feeling that my dateComponents could be overdetermined. I therefore introduced a nextEvent that only contained the day hour and minute of the dateComponents:

 var nextEvent = DateComponents()
 nextEvent.day = dateComponents.day
 nextEvent.hour = dateComponents.hour
 nextEvent.minute = dateComponents.minute
        
 let trigger = UNCalendarNotificationTrigger(dateMatching:nextEvent, repeats: false)

when I now invoke trigger.nextTriggerDate() it becomes

nextDate = Optional(2017-01-08 20:34:00 +0000)

as it should. But I do not understand why I cannot use the dateComponents when I create the trigger.

Community
  • 1
  • 1
ragnarius
  • 5,642
  • 10
  • 47
  • 68

1 Answers1

9

During my tests I found dateComponents.quarter = 0 to be the cause of the problems. Zero quarter is obviously wrong, it should be quarter = 1 It seems there is an old bug that causes the date components to have an invalid quarter.

If you manually set dateComponents.quarter = 1 or just dateComponents.quarter = nil, everything starts to work.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • 2
    I edited out the previous answer because it wasn't very specific. I think I found the real cause of the problem. – Sulthan Jan 07 '17 at 21:40
  • Thanks, who would think that date components returned from `calendar.dateComponents(in: timeZone, from: date)` are incorrect for local notifications. – Aliaksandr Bialiauski Apr 30 '21 at 07:48