2

Using Swift5.2, iOS13.4,

I try to set a local Notification that fires on a particular date and repeats every minute endlessly.

I tried using Calendar.components and UserNotification in the following way:

// create alarmDate in the future
let formatter = DateFormatter()
formatter.dateFormat = "yyyy/MM/dd HH:mm"
let alarmDate = formatter.date(from: "2020/05/15 20:31") ?? Date()

let repeatesBool = true  // the alarm shall repeat every minute
let calendarComponentSet: Set<Calendar.Component> = [.second]  // mask to repeat every minute

let alarmIdentifier = "myID1234"
let triggerKind = Calendar.current.dateComponents(calendarComponentSet, from: alarmDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerKind, repeats: repeatesBool)                
let request = UNNotificationRequest(identifier: alarmIdentifier, content: content, trigger: trigger)

notificationCenter.add(request) {(error) in 
    if let error = error { print("error: \(error)") } 
}

.

The problem:

Once I execute the above code at any time on the alarmDate, the alarm starts firing immediately (instead of when the alarmDate-time, i.e. hour and minute actually are reached). Or in other words: when the alarmDate should start at 20:31 time, and I execute the above code at for example 16:00, then it already fires the alarm (instead of at 20:31 as expected). Why is that ?

In the above code, if I set the calendarComponentSet as follows, I do get the alarm firing off at the correct date AND time - but then it does not repeat every minute as intended :

let calendarComponentSet: Set<Calendar.Component> = [.day, .month, .year, .hour, .minute, .second]

So the question:

How do you create a local Notification that fires on a particular date AND time and repeats every minute endlessly thereafter ???

(The goal is to spend only one local notification for this).

iKK
  • 6,394
  • 10
  • 58
  • 131

0 Answers0