I've created a scheduled notification and I'd like to be able to do stuff once it gets delivered. Not once it's clicked on or selected, but when it's actually delivered and shows up on the user's screen.
The code I've used to generate the notification is:
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "foo", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "bar", arguments: nil)
var dateInfo = DateComponents()
dateInfo.hour = 7
dateInfo.minute = 0
print(dateInfo.hour!)
print(dateInfo.minute!)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: false)
// Create the request object.
let notificationRequest = UNNotificationRequest(identifier: "MorningAlarm", content: content, trigger: trigger)
center.add(notificationRequest)
I'm sure I've got to add something to my AppDelegate that'll respond when the notification is delivered, but I've been looking all over the internet and can't find a way to do it on delivery rather than on select.
When a notification arrives, the system calls the userNotificationCenter(_:willPresent:withCompletionHandler:)
method of the UNUserNotificationCenter object’s delegate.
let center = UNUserNotificationCenter.current()
center.delegate = self // What delegation target Here is my AppDelegate
extension AppDelegate : UNUserNotificationCenterDelegate {
// while your app is active in forground
// Handle Notifications While Your App Runs in the Foreground
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Change this to your preferred presentation option
// Play a sound.
// completionHandler(UNNotificationPresentationOptions.sound)
}
// While App is inactive in background
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// While App is inactive in background
print(userInfo)
completionHandler()
}
}