0

I need to create different types of notifications. I managed to create a notification at a specific date, but now I need to create one that repeats daily, after a start date. It's basically a reminder to take a daily medication, but the user will only start taking that medication at a specific day.

Here is my func:

func addNotification(text: String, date: Date, id: String) {
   let content = UNMutableNotificationContent()
   content.title = "My App"
   content.body = text
   content.sound = .default
   content.badge = NSNumber(integerLiteral: UIApplication.shared.applicationIconBadgeNumber + 1)

   var dateComponents = DateComponents()
   dateComponents.hour = Calendar.current.component(.hour, from: date)
   dateComponents.minute = Calendar.current.component(.minute, from: date)

   var trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

   let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)

   UNUserNotificationCenter.current().add(request) { error in
      if let error {
         print(error.localizedDescription)
      }
   }
}

As it is, it will notify daily, but from the moment the func is fired. I need to receive a start date and only begin firing after that. One thing that comes to mind is: if I also specify the year, month and day on "dayComponents" like this:

dateComponents.hour = Calendar.current.component(.hour, from: date)
dateComponents.minute = Calendar.current.component(.minute, from: date)
dateComponents.day = Calendar.current.component(.day, from: date)
dateComponents.month = Calendar.current.component(.month, from: date)
dateComponents.year = Calendar.current.component(.year, from: date)

and set the trigger to repeat, would it consider all the parameters (hour, minute, day, month, year) and never repeat (as this day will never happen again), or will it only consider hour and minute to repeat? I wanted to try that, but then I'd need to wait for a whole day, so maybe someone here knows the answer!

burnsi
  • 6,194
  • 13
  • 17
  • 27
  • https://stackoverflow.com/questions/68980169/repeating-local-notifications-for-specific-days-of-week-after-certain-start-date – tanmoy Feb 10 '23 at 21:25
  • @MuhtasimUlfatTanmoy that particular question doesn't have an answer... It mentions another post, but that other post also doesn't answer the question... – Hugo Silva Feb 10 '23 at 21:44

0 Answers0