Search code examples
iosswiftuilocalnotificationunnotificationrequest

UNUserNotification never appear when scheduled for later date


Notifications are shown when I schedule for a near date in the future, like 1 hour later, but they never show on my real data, when I schedule for tomorrow or for later tonight. Any ideas on why this is happening? I double checked the trigger.nextTriggerDate(), they are right

Here's my code:

@available(iOS 10.0, *)
class func scheduleWith(episode: Episode, dateInfo: DateComponents) {
    let content = UNMutableNotificationContent()
    content.title = episode.title
    content.body = episode.overview

    content.userInfo = ["id": episode.id]
    content.categoryIdentifier = Notify.category.episodes.str

    let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: false)

    let request = UNNotificationRequest(identifier: Notify.identifier.episode.str, content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
        if let error = error {
            print(error)
        }
        else {
            print("date info", dateInfo.date)
            print("trigger", trigger.nextTriggerDate()!)
        }
    })
}

And here's how I'm creating the dateInfo:

let greg = Calendar.current
var components = DateComponents()
components.setValue(-15, for: .minute)

guard let date = ep.firstAired as Date? else { return }
guard let alertDate = greg.date(byAdding: components, to: date) else { return }

let dateInfo = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second], from: alertDate)

Solution

  • You are using the same identifier for your notifications. You need to specify a different identifier to each notification inside your loop.