0

Currently, I am trying to get an event to trigger after a user has received a notification. Notifications are appearing at the correct time. However, the function that checks for delivered notifications never shows any delivered notifications. I have verified that the code is running, it always prints 0 for the count of delivered notifications.

This is how I am checking for delivered notifications:

UNUserNotificationCenter.current().getDeliveredNotifications(completionHandler: { deliveredNotifications -> () in 
    print(deliveredNotifications.count)
})

And this is how I'm creating notifications:

let content = UNMutableNotificationContent()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE, MMM d yyyy, hh:mm a"
let date:Date = dateFormatter.date(from: date)!

content.body = "Notification occurred"
content.sound = UNNotificationSound.default()
let timeInterval = date.timeIntervalSinceNow
if timeInterval > 0.0 {
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 
    timeInterval, repeats: false)
    let request = UNNotificationRequest(identifier: id, content: 
    content, trigger: trigger)
    UNUserNotificationCenter.current().add(request, 
    withCompletionHandler: nil)
}

How can I get a portion of code to execute after a notification has been delivered?

  • When do you check the delivered notification count? ie. which function is the code you have shown in? – Paulw11 Apr 28 '17 at 04:00
  • I check it in the table view controller where I want to add an entry once a notification occurs, in viewDidLoad() – bluecandle Apr 28 '17 at 04:05
  • 1
    This function would need to be called repeatedly in order to get any newly added notification details, so `viewDidLoad` probably won't help you. Local notifications will only be added to the notification center while your app is in the background, so it would probably make most sense to call this function when your app returns to the foreground – Paulw11 Apr 28 '17 at 04:08
  • So if the app is in the foreground, it will not be added to the notification center? I know actions exists for notifications, but those seem to be user initiated. Is there another route to have some kind of callback occur after a notification is delivered? – bluecandle Apr 28 '17 at 04:14
  • Yes, you can use the [`UNUserNotificationCenterDelegate`](https://developer.apple.com/reference/usernotifications/unusernotificationcenterdelegate) methods – Paulw11 Apr 28 '17 at 04:16
  • Okay, thanks. Will look into it! – bluecandle Apr 28 '17 at 04:20

0 Answers0