How to show a Push Notification while the app is in foreground
Posted: | Author: Jörn | Filed under: iOS, Swift | Tags: APN, PushNotification, UserNotifications | 1 Comment »I currently work on a project where we use Apple’s User Notifications (formerly known as Push Notifications) to deliver chat messages to our users. Whenever the user is not in the chat screen we want to show the Notification using the standard system banner on top of the screen.
Per default when a User Notification is received while the app runs in the foreground the notification is not shown to the user. With the arrival of Apple’s iOS10 UserNotifications framework you can easily decide whether to show the received Notification or not. When a Notification is delivered to a foreground app the UNUserNotificationCenterDelegate method userNotificationCenter(_:willPresent:withCompletionHandler:) is called. By calling this method’s completionHandler you tell the system if and how it should show the Notification to the user:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// do your stuff
// this tells the system NOT to show the notification to the user
completionHandler()
}
If you want to show the notification you can add a set of UNNotificationPresentationOptions to the completion handler:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// do your stuff
// this tells the system to show the notification to the user with sound
completionHandler([.alert, .sound])
}
If you don’t want to play the notification sound while the app is running in the foreground you can simply omit the sound option:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// do your stuff
// this tells the system to show the notification to the user without sound
completionHandler(.alert)
}