Get Push Notification While App in Foreground iOS in Swift

by

If the application is running in the foreground, iOS won’t show a notification banner or alert. That is by design.

If we receive local or remote notifications while we app is running in the foreground, we’re responsible for passing the information to our users in an app-specific way. Where to handle and process such request?

userNotificationCenter(_:willPresent:withCompletionHandler:)

Asks the delegate how to handle a notification that arrived while the app was running in the foreground.

If your app is in the foreground when a notification arrives, the shared user notification center calls this method to deliver the notification directly to your app. If you implement this method, you can take whatever actions are necessary to process the notification and update your app. When you finish, call the completionHandler block and specify how you want the system to alert the user, if at all.


How to show native default notification in foreground similar to when app is in background?




func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    if UIApplication.shared.applicationState == .active {
        completionHandler( [.alert,.sound])
    }
}

completionHandler will show alert and sound from foreground app, just like a push that is shown from background app.

More Articles

Recommended posts