1

I am scheduling daily repeating notifications by setting only hour, minutes and seconds:

func addNotification(fireDate: Date)
{
    let notificationCenter = UNUserNotificationCenter.current()
    let content = UNMutableNotificationContent()
    content.title = "Some title"
    content.body = "Some message"
    content.sound = .default
    content.categoryIdentifier = "MyCategory"
        
    let calendar = Calendar(identifier: .gregorian)
    let triggerDate = calendar.dateComponents([.hour, .minute, .second], from: fireDate)
    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)

    let requestID = UUID().uuidString
    let notificationRequest = UNNotificationRequest(identifier: requestID, content: content, trigger: trigger)
    notificationCenter.add(notificationRequest) { error in
            
        if let error = error
        {
            print(error.localizedDescription)
        }
    }
}

Now I would like to be able to cancel all notifications for current day, so I could receive notifications starting with tomorrow. I tried to subclass UNCalendarNotificationTrigger in order to change nextTriggerDate, but there is an error when adding a notification using my custom trigger class. Cannot find a way to achieve this, if I cancel a scheduled notification at certain time, I will not receive that notification anymore. Any ideas are appreciated.

iOS Dev
  • 4,143
  • 5
  • 30
  • 58
  • Cancel the notification, and create a new one starting from a new `fireDate` tomorrow. (Though if the notification doesn't impact the user, I typically would just receive it anyway, and ignore it. That's can handle much more complex situations.) – Rob Napier Sep 02 '20 at 15:16
  • @RobNapier I use only hours, minutes and seconds, other date components are ignored. – iOS Dev Sep 02 '20 at 15:24
  • What's wrong with Rob Napier's suggestion? You set the `from: fireDate`, cancel the one you want, and recreate one setting the fireDate as tomorrow. – Larme Sep 02 '20 at 15:52
  • 1
    @Larme Example: A notification is set to repeat everyday at 4:00 PM. Right now is 2:00 PM and I would like not to receive the notification for today. If I cancel the notification and recreate using fireDate as tomorrow it will change nothing, notification will show up today at 4:00 PM, because I take from date only hour, minutes and seconds, it doesn't matter if fireDate is from today, tomorrow or any other day. – iOS Dev Sep 02 '20 at 16:04
  • The short answer is you can't do it with a single, repeating notification. You would need to create a series of notifications for the next few days and cancel the specific notification for today. – Paulw11 Sep 02 '20 at 16:06
  • 1
    @Paulw11 I guess you are right. With old approach UILocalNotification this was easily achievable because it has a property fireDate. The new UNNotificationTrigger is powerful, but it misses this feature. – iOS Dev Sep 03 '20 at 06:12

0 Answers0