Scheduling a timed notification

A timed notification is the simplest notification to schedule, which makes it a great candidate to explore first. Timed notifications are scheduled with an instance of UNTimeIntervalNotificationTrigger. The initializer for this class takes a time interval and a boolean value to indicate whether the notification should be sent to the user repeatedly. Add the following method to the NotificationHelper:

func scheduleTimedNotificationWithContent(_ content: UNNotificationContent) {
  let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
  let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
  notificationCenter.add(request) { error in
    if let error = error {
      print(error.localizedDescription)
    }
  }
}

The preceding method creates a trigger for the notification. In this case, the notification is set up to fire after 10 seconds have passed. Next, a notification request is created. Every notification request should have an identifier. In this case, a very simple identifier is used to identify the timed notification. After creating the notification, it is added to the notification with a completion handler.

The identifier attribute for a notification should be unique for the content of the notification. The system uses this identifier to avoid sending multiple notifications with the same content. If you send multiple notifications with the same identifier, the last notification you sent will be shown to the user. If you want to display multiple notifications in the Notification Center, you should make sure that every notification you schedule has a unique identifier.

If you want to send a repeating notification to a user, you must set the repeats property for the time interval trigger to true.

The minimum time interval for repeating notification is 60 seconds. Scheduling a repeating trigger with an interval under 60 seconds will crash your application.

To test the interval-based notification, you can add a call to scheduleTimedNotificationWithContent(_:) in AddNotificationViewController in the addBedtimeNotification() or addLunchTimeNotification() methods, after the following line:

try? self.persistentContainer.viewContext.save()

The following code can be added to schedule the timed notification:

let content = notificationsHelper.createNotificationContentForReminder(reminder)
    notificationsHelper.scheduleTimedNotificationWithContent(content)

If you run the app now, and schedule a reminder before going to your device's home screen or the lock screen, a notification about the reminder should appear after about 10 seconds. The following screenshot shows an example of a lunchtime reminder:

The next notification you will explore is the calendar based notification.