iosobjective-cswiftapple-push-notificationsunnotificationserviceextension

UNNotificationServiceExtension - hide when app is active


I'm using UNNotificationServiceExtension to add images to iOS APNS notifications. It works well except that the notification displays even when the app is active (in the foreground). When the app is active I'd like handle notifications using a toast, and not show the standard iOS notification over the top of the active app.

Q: Is there a way to detect the app's state from within the Notification Service Extension and block the notification from displaying when the app is active?


Solution

  • Based on Apple's documentation notifications shouldn't appear when the app is active by default.

    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.

    It doesn't matter if you use the notification service extension - a notification is always handled by the app in the end, the extension can be used to modify it first though.

    Try this code (in fact, since notifications appear while the app is active, you probably have this method implemented somewhere - if you don't need it you can just remove it).

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    
        // Perform additional handling of the notification, if needed.
    
        completionHandler([])
    }