dertobiaszwei
dertobiaszwei

Reputation: 99

How to setup period (time period) for Notifications?

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!

Upvotes: 0

Views: 212

Answers (1)

Vincent Joy
Vincent Joy

Reputation: 2678

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

Upvotes: 0

Related Questions