I like the smell of Swift in the morning…

How to show a Push Notification while the app is in foreground

Posted: | Author: | Filed under: iOS, Swift | Tags: , , | No Comments »

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:

If you want to show the notification you can add a set of UNNotificationPresentationOptions to the completion handler:

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: