iosswiftusernotifications

How to set alerts in UNNotificationCenter some days before?


How I can make local notification be triggered before some days? For example, I create local notifications from dateComponents:

    var dateComponents = Calendar.current.dateComponents([.month, .day], from: birthDate)
    dateComponents.hour = 10
    dateComponents.minute = 30
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

I get days from:

var dateComponents = Calendar.current.dateComponents([.month, .day], from: birthDate).

But how I can set them triggered before one day at specifiс time?


Solution

  • if let oneDayAgo = Calendar.current.date(byAdding: .day, value: -1, to: birthDate) {
        var dateComponents = Calendar.current.dateComponents([.month, .day], from: oneDayAgo)
        dateComponents.hour = 10
        dateComponents.minute = 30
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
    }