Scheduling a calendar-based notification

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

Go right ahead and add the following method to NotificationsHelper to create a notification that is fired every hour, on the hour:

func scheduleHourlyWaterReminder() {
  let content = UNMutableNotificationContent()

  content.title = "Reminder"
  content.body = "This is your reminder to drink some water every hour."

  var hourComponents = DateComponents()
  hourComponents.minute = 0

  let trigger = UNCalendarNotificationTrigger(dateMatching: hourComponents, repeats: true)
  let request = UNNotificationRequest(identifier: "water-notification", content: content, trigger: trigger)

  notificationCenter.add(request) { error in
    if let error = error {
      print(error.localizedDescription)
    }
  }
}

The preceding code sets up a trigger that fires every hour when the value of the minutes component is 0. Since this notification should trigger every hour, the repeats argument is set to true.

Since the user can choose to turn off the water reminder, you should also implement a method to remove the repeating notification. Add the following method to the notifications helper to do this:

func unscheduleHourlyWaterReminder() {
  notificationCenter.removePendingNotificationRequests(withIdentifiers: ["water-notification"])
}

Next, update drinkWaterNotificationToggled(sender:) in the add notifications view controller, so that scheduleHourlyWaterReminder() is called when the switch is on and unscheduleHourlyWaterReminder() is called when the switch is off.

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.9.7