Scheduling a calendar-based notification

Calendar-based notifications make use of DateComponents() to determine when they should be fired. The only difference with time-interval-based scheduling is in the trigger we use to determine when the notification should be displayed.

Let's dive right in and look at an example of how a calendar-based trigger can be set up:

var components = DateComponents()
components.day = 1
components.hour = 8

let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)

The preceding code sets up a trigger that fires on the first day of the month at 08:00 AM. If we want this notification to trigger every month, we just need to set the repeats property to true. Setting the notification as shown in the code will fire the notification the very next time it's 08:00 AM on the first day of a month. Date() components are very powerful because you could even use them to schedule a notification that fires next week on the current day. The following example shows how you would set up the dateComponents for this.

let cal = Calendar.current
var components = cal.dateComponents([.year, .weekOfYear, .day], from: Date())
let scheduleWeek = components.weekOfYear! + 1
components.weekOfYear = scheduleWeek > 52 ? 1 : scheduleWeek
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)

We fetch the user's current calendar and use it to extract the year, day, and the week of the year from the current date. Then we increment the week of the year by 1 and that's all we have to do. A ternary operator is used to do a quick check to make sure that we don't schedule notifications in a non-existing week.

Calendar-based notifications provide a powerful way for you to schedule both recurring and one-time-only notifications that are tied to being fired at a certain offset in time that's easier to express in days, hours, weeks, or months than it in a time interval.

TheĀ The Daily Quote app is a great candidate for calendar-based notifications. Try to implement a notification that fires every day at 08:00 AM so your users have a fresh quote to read every morning.