> For the complete documentation index, see [llms.txt](https://docs.payments.thalescloud.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.payments.thalescloud.io/nfc-wallet-sdk-ios/es/get-started/configuration/4.-push-notifications/handle-push-notifications.md).

# Gestionar notificaciones push

NFC Wallet utiliza notificaciones push para notificar a tu **aplicación de billetera digital**. Las notificaciones son enviadas por el backend de NFC Wallet.

{% hint style="info" %}
El manejo de notificaciones push de NFC Wallet es necesario para admitir **LCM**, notificaciones de transacciones y flujos de registro de tarjetas donde la tarjeta digital es activada directamente por el emisor.
{% endhint %}

### Enruta las notificaciones usando `remitente`

Leer `userInfo["sender"]` y dirigir la notificación al manejador correcto:

* `CPS`: operaciones de tarjeta digital (**LCM**)
* `TNS`: notificaciones de transacciones
* `MG`: reposición de claves de pago activada por el **TSP**

```swift
func application(
    _ application: UIApplication,
    didReceiveRemoteNotification userInfo: [AnyHashable : Any],
    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
    let sender = userInfo["sender"] as? String

    Task {
        do {
            switch sender {
            case "CPS":
                // Operaciones de tarjeta digital (LCM).
                // Llama al manejador de notificaciones del SDK. Ver `NotificationService` en la referencia de la API.
                break

            case "TNS":
                // Notificaciones de transacciones.
                // Actualiza el historial de transacciones. Ver `TransactionHistoryService` en la referencia de la API.
                break

            case "MG":
                // Reposición de claves activada por el TSP.
                // Inicia la reposición. Ver `ReplenishmentService` en la referencia de la API.
                break

            default:
                // Notificaciones no pertenecientes al SDK.
                break
            }

            completionHandler(.newData)
        } catch {
            completionHandler(.failed)
        }
    }
}
```

### Procesar notificaciones CPS (operaciones de tarjeta digital)

Reenviar **CPS** notificaciones push al SDK usando `NotificationService.processNotification()`.

<pre class="language-swift"><code class="lang-swift">let notification = NotificationService()
<strong>do {
</strong>    try await notification.processNotification(forUserInfo: userInfo)
} catch {
    // mostrar el error
}
</code></pre>

El SDK de NFC Wallet procesa el push e interactúa con el backend de NFC Wallet.

El SDK puede entonces emitir eventos de notificación a través de `NotificationService.notificationEventStream`. Usa estos eventos para seguir la operación de la tarjeta digital.

Eventos compatibles:

* `unsupportedPushContent`: Se desencadena cuando la carga útil del push no es compatible con el SDK.
* `completed`: Se desencadena cuando el procesamiento finaliza correctamente (por ejemplo, después de provisionar un perfil de tarjeta y claves de pago).
* `serverMessage`: Se desencadena cuando el backend devuelve una instrucción. El SDK proporciona un `serverMessage` objeto y un `tokenizedId`.

#### Mensaje del servidor

Cuando reciba `serverMessage`, analiza el `serverMessage` objeto para determinar qué operación solicitó el backend.

En particular:

* `requestInstallCard`: Solicitud para instalar una tarjeta.
* `requestResumeCard`: Solicitud para mover una tarjeta de suspendida a activa.
* `requestSuspendCard`: Solicitud para mover una tarjeta de activa a suspendida.
* `requestDeleteCard`: Solicitud para eliminar una tarjeta.

### Procesar notificaciones TNS (transacciones)

Las notificaciones de transacciones proporcionan detalles sobre transacciones de pago completadas. Usa `TransactionHistoryService` para recuperar registros de transacciones.

A través de la notificación push, el **aplicación de billetera digital** obtiene la siguiente información a través del `userInfo` del parámetro de la notificación:

* `userInfo["sender"]`: `TNS`.
* `userInfo["action"]`: `TNS:PaymentTransactionNotification`.
* `userInfo["digitalCardId"]`: Identificador de la tarjeta digital. Úsalo con `TransactionHistoryService.records(forDigitalCardID:)`.
* `userInfo["transactionRecordType"]`: Presente solo para tarjetas con doble marca. Pásalo a `TransactionHistoryService.records(forDigitalCardID:transactionRecordType:)` para recuperar solo los registros relevantes (primario o auxiliar).

<pre class="language-swift"><code class="lang-swift">let action = userInfo["action"] as? String
let cardId = userInfo["digitalCardId"] as? String
let recordType = userInfo["transactionRecordType"] as? String

// Verificar la acción esperada y la presencia del id de la tarjeta.
guard "TNS:PaymentTransactionNotification" == action, let cardId = cardId else {
    // mostrar el error
}

let historyService = TransactionHistoryService()
do {       
<strong>    let records = try await historyService.records(forDigitalCardID: cardId, transactionRecordType: recodType)
</strong>} catch {
    // mostrar el error
}
</code></pre>

### Procesar notificaciones MG (reposición)

El **TSP** puede solicitar la reposición de claves de pago. Usa `ReplenishmentService` para reponer claves.

A través de la notificación push, el **aplicación de billetera digital** obtiene la siguiente información a través del `userInfo` del parámetro de la notificación:

* `userInfo["sender"]`: `MG`.
* `userInfo["action"]`: `MG:ReplenishmentNeededNotification`.
* `userInfo["digitalCardId"]`: Identificador de la tarjeta digital. Úsalo con `ReplenishmentService.replenish(digitalCardID:isForced:)`.

<pre class="language-swift"><code class="lang-swift">let action = userInfo["action"] as? String
let cardId = userInfo["digitalCardId"] as? String

// Verificar la acción esperada y la presencia del id de la tarjeta.
guard "MG:ReplenishmentNeededNotification" == action, let cardId = cardId else {
    // mostrar el error
}

let replenishmentService = ReplenishmentService()
do {       
<strong>    try await replenishmentService.replenish(digitalCardID: cardId, isForced: true)
</strong>} catch {
    // mostrar el error
}
</code></pre>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.payments.thalescloud.io/nfc-wallet-sdk-ios/es/get-started/configuration/4.-push-notifications/handle-push-notifications.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
