# ASWebAuthenticationSession

For iOS usage, using ASWebAuthenticationSession is one of the recommended approaches.

After creating the transaction and obtaining the transaction link, the following implementation is recommended:

* In your regular flow (which includes IDPay), you will open the ASWebAuthenticationSession with the link generated via API.
* You can customize this opening in the way that works best for your app.
* You will monitor if the URL has changed (to the redirectUrl) and then close the page.

To make the flow work, you need to follow the following steps:

## Step 1: Create the Payment Authentication Controller

The first step is to create the payment authentication controller. To do this, create a class called **`IDPayAuthenticationController`** (or any name you prefer).

Next, import the **`AuthenticationServices`** framework at the top of the class.

Declare the class as **`NSObject`** and implement the `ASWebAuthenticationPresentationContextProviding` protocol.

The result should be:

```swift
import AuthenticationServices

class IDPayAuthenticationController: NSObject, ASWebAuthenticationPresentationContextProviding {
    func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
           if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
               if let mainWindow = windowScene.windows.first {
                   return mainWindow
               }
           }
           return ASPresentationAnchor()
       }
}
```

## Step 2: Implement Authentication

Open the file where you will perform the authentication and add the necessary imports (in our example, we are doing this in ContentView\.swift).

```swift
import SwiftUI
import AuthenticationServices
```

To control the authentication state, we will create a @State property.

```swift
@State private var isAuthenticated = false
```

Create an instance of the IDPayAuthenticationController class outside the body of the ContentView structure.

```swift
let idPayController = IDPayAuthenticationController()
```

To validate the payment, create a function called authenticatePayment.

```swift
func authenticatePayment() {
    guard let url = URL(string: "URL_AUTHENTICATION") else { return }

    var session: ASWebAuthenticationSession?
    session = ASWebAuthenticationSession(url: url, callbackURLScheme: "BUNDLE") { callbackURL, error in
        guard callbackURL != nil else {
            if let error = error {
                return print("Erro durante a autenticação: \(error.localizedDescription)")
            }
            return
        }

        // Processa o URL de callback para verificar se a autenticação foi bem-sucedida
        session?.cancel()
        isAuthenticated = true
    }

    session?.presentationContextProvider = idPayController
    session?.prefersEphemeralWebBrowserSession = true
    session?.start()
}
```

{% hint style="danger" %}
Remember to change the URL\_AUTHENTICATION to the authentication URL received in your transaction and also the callbackURLScheme BUNDLE to the redirect provided when creating your transaction (we recommend using the Bundle Identifier of your app).
{% endhint %}

{% hint style="info" %}
It is important to set prefersEphemeralWebBrowserSession to true to ensure a unique authentication per transaction.
{% endhint %}

Example of how it should look in the app:

<figure><img src="https://4215638879-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FwXjg7k5gG7wmNiFGOIuw%2Fuploads%2FcqRyWRGafBm0kiGVxmSI%2Fw.gif?alt=media&#x26;token=29a1b50e-40bc-43ee-9285-f74f01d618d8" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Some permissions are required for it to work properly, such as:

* Camera;
* Geolocation.
  {% endhint %}

For more information, we recommend reading the following articles and documentation:&#x20;

To access the official documentation, click [<mark style="color:blue;">**here**</mark>](https://developer.apple.com/documentation/webkit/wkwebview).


---

# Agent Instructions: 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://devcenter.unico.io/unico-idpay/en/integration/controlling-the-experience/mobile/ios/aswebauthenticationsession.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.
