Fix: Detecting a Push Notification Tap When the App Is in Background

Fix: Detecting a Push Notification Tap When the App Is in Background

Written by

in

Quick answer: Route from userNotificationCenter(_:didReceive:withCompletionHandler:), not from application(_:didReceiveRemoteNotification:fetchCompletionHandler:). The first fires only when the user taps the notification; the second fires on delivery whenever Background Modes → Remote notifications is enabled and the payload contains content-available: 1.

Why this happens

Two different events get conflated: the notification arriving and the user tapping it.

application(_:didReceiveRemoteNotification:fetchCompletionHandler:) is a delivery callback. When the target has Background Modes → Remote notifications enabled and the payload contains "content-available": 1, iOS wakes the app in the background and calls this method as soon as the notification lands. At that moment application.applicationState is .background — the user has not touched anything yet, and may never.

The tap callback is a separate API. Since iOS 10 it is UNUserNotificationCenterDelegate.userNotificationCenter(_:didReceive:withCompletionHandler:), which fires only when the user taps the notification body or one of its action buttons. That is the method to route from.

The workaround of unchecking Remote notifications does make the old delegate fire only on tap, but it also disables silent and background push for the whole app. That is a bad trade if you rely on content-available.

How to fix it

1. Adopt UNUserNotificationCenterDelegate

Create a small router object and make it the notification center delegate. Set the delegate before application(_:didFinishLaunchingWithOptions:) returns, otherwise a cold launch from a tap can be missed.

import UIKit
import UserNotifications

final class NotificationRouter: NSObject, UNUserNotificationCenterDelegate {

    static let shared = NotificationRouter()
    private var handled: Set<String> = []

    func start() {
        UNUserNotificationCenter.current().delegate = self
    }

    // App is in the foreground: this is a delivery, not a tap.
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
    ) {
        completionHandler([.banner, .sound, .badge]) // .banner is iOS 14+
    }

    // The user tapped the notification body or one of its actions.
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        handle(response)
        completionHandler()
    }

    func handle(_ response: UNNotificationResponse) {
        // Ignore dismissals and custom actions unless you handle them.
        guard response.actionIdentifier == UNNotificationDefaultActionIdentifier else { return }

        let id = response.notification.request.identifier
        guard handled.insert(id).inserted else { return } // avoid double routing

        let userInfo = response.notification.request.content.userInfo
        guard let deepLink = userInfo["deep_link"] as? String else { return }
        // Navigate to the screen named by deepLink.
    }
}

Wire it up in the app delegate:

func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
    NotificationRouter.shared.start()
    application.registerForRemoteNotifications()
    return true
}

2. Stop routing from the delivery callback

Keep didReceiveRemoteNotification for what it is actually for — refreshing data — and never push UI from it.

func application(
    _ application: UIApplication,
    didReceiveRemoteNotification userInfo: [AnyHashable: Any],
    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
    // Delivery only. The user may never open this notification.
    refreshData { completionHandler(.newData) }
}

3. Handle cold launch in a scene-based app

When the app is not running and the user taps a notification, the response also arrives in the scene connection options. Pass it to the same router method so both paths behave identically.

func scene(
    _ scene: UIScene,
    willConnectTo session: UISceneSession,
    options connectionOptions: UIScene.ConnectionOptions
) {
    if let response = connectionOptions.notificationResponse {
        NotificationRouter.shared.handle(response)
    }
}

The handled set in step 1 matters here: on some launches the delegate callback and the scene connection options both fire for the same notification, and without the guard you would push the same screen twice.

4. If you are stuck on the old delegate: check applicationState

Apps that cannot move to UNUserNotificationCenter yet can still read the state inside the fetch-completion callback. .inactive is the state the app is in while it transitions from background to foreground because of a tap.

func application(
    _ application: UIApplication,
    didReceiveRemoteNotification userInfo: [AnyHashable: Any],
    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
    switch application.applicationState {
    case .active:
        break // already in the foreground
    case .inactive:
        route(userInfo) // user tapped the notification
    case .background:
        break // delivered in the background, no tap yet
    @unknown default:
        break
    }
    completionHandler(.newData)
}

Treat this as a heuristic. .inactive also occurs during other transitions, such as pulling down Control Center or the app switcher. The UNUserNotificationCenter delegate has no such ambiguity.

5. Test both paths in the Simulator

Build a payload file and push it with simctl:

{
  "aps": {
    "alert": { "title": "New order", "body": "Tap to open" },
    "content-available": 1
  },
  "deep_link": "myapp://orders/42"
}
xcrun simctl push booted com.example.app payload.apns

Background the app, push, then tap the banner — the router should fire. Push again and open the app from the Home Screen icon instead — nothing should be routed. If the second case also navigates, you are still routing from the delivery callback.

How to prevent it

  • Route only from userNotificationCenter(_:didReceive:withCompletionHandler:).
  • Assign the delegate before didFinishLaunchingWithOptions returns.
  • Keep content-available data refresh and tap navigation in separate code paths.
  • Dedupe by response.notification.request.identifier when you also read connectionOptions.notificationResponse.
  • Log the payload and applicationState during development so you can see which callback fired and when.

FAQ

Why is didReceiveRemoteNotification called before the user taps?

Because Background Modes → Remote notifications is enabled and the payload carries "content-available": 1. iOS delivers the payload in the background immediately so the app can refresh its data, and the callback fires at that moment, not at tap time.

Does this work for local notifications too?

Yes. UNUserNotificationCenterDelegate handles both local and remote notifications. Only the payload parsing differs — the tap callback and the routing logic are the same.

What happens if the app was force-quit?

Tapping the notification launches the app and the delegate’s didReceive is called, provided the delegate is set early enough during launch. Background delivery does not happen after a force-quit, so a silent push will not wake the app until the user opens it again.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.