0

I want to setup a time period for my Notifications. I created a UNTimeIntervalNotificationTrigger, that the App sends everyday 3 Notifications. But I also want to do that the 3 Notifications will send between 10:00am and 11:00am or whatever.

So anyone knows how to code a time period for Notifications, that the App sends in that period a few Notifications?

Thank you!

1 Answers1

0

Instead of UNTimeIntervalNotificationTrigger, you should use UNCalendarNotificationTrigger

But for 3 notifications between 10AM and 11AM, you need to create 3 notifications.

func scheduleNotification(hour: Int, minute: Int) {

    let center = UNUserNotificationCenter.current()

    let content = UNMutableNotificationContent()
    content.title = "Your title"
    content.body = "Your body"
    content.categoryIdentifier = "AlarmAt\(hour)\(minute)"
    content.userInfo = ["customKey": "customValue"]
    content.sound = UNNotificationSound.default

    var dateComponents = DateComponents()
    dateComponents.hour = hour
    dateComponents.minute = minute
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

    center.add(request)
}

scheduleNotification(hour: 10, minute: 15)
scheduleNotification(hour: 10, minute: 30)
scheduleNotification(hour: 10, minute: 45)

More Info :-

To better understand the scope of UNCalendarNotificationTrigger , I am adding some more options. Note, for your requirement you shouldn't add the below 2 lines, it will give you unexpected results.

If you want this to repeat only any particular day in the week, add :-

dateComponents.weekday = 2 // Only mondays

If you want this to repeat only any particular day in a month, add :-

dateComponents.day = 12 // Only 12th day of the month
Vincent Joy
  • 2,598
  • 15
  • 25
  • Hey, thank you! One other question. How would you do it when the user can choose how many Notifications he want in that one hour? Thank you and have a nice day – dertobiaszwei Jun 02 '20 at 13:05
  • Then you need to create as many notification requests as that of user selected. Collect the user inputs (hour and minute) in an array and loop through it to call this scheduleNotification method. Because only UNTimeIntervalNotificationTrigger allows to set time interval whereas UNCalendarNotificationTrigger only allows to set the time. Both together will not work. – Vincent Joy Jun 02 '20 at 13:17