> This page is for Applications Protection.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.humansecurity.com/llms.txt.

# visionOS integration (Window)

> **Note**
>
> This guide is relevant for the current Mobile SDK. While we highly recommend using the latest version, if you are using a legacy integration, refer to the [iOS](/applications/ios-how-to-integrate-the-sdk-in-your-application-v3) or [Android](/applications/android-how-to-integrate-the-sdk-in-your-application-v3) documentation.

You can integrate the SDK with your visionOS app to display the HUMAN Challenge in a separate window. THis window cna be moved by the user and doens't block them from interacting with the rest of your application. However, once blocked, calls won't go through until the Challenge is resolved.

The code is integrated once and covers all request sent from anywhere in your app, including the background and foreground. You can learn how to integrate with this article.

> **Warning**
>
> Some features that are supported in iOS, including the Doctor App, Automatic Interceptor, and Hybrid App support, are not available in the SDK for visionOS.

## Prerequisites

* [Enable multiple windows](https://developer.apple.com/documentation/visionos/presenting-windows-and-spaces#Enable-multiple-simultaneous-scenes) in your app's `Info.plist`.

## Start the SDK

When starting the SDK, keep the following in mind:

1. **Start the SDK as soon as possible** in your app's flow. We recommend doing so in the `App`'s `init` function in visionOS. If you don't do this, then your application may send a URL request to your server before the SDK starts. This means the request will not include HTTP headers that indicate whether the request is legitimate, and as a result:
   * The

     Enforcer

     may block the request instead, and
   * The SDK will not be able to present a challenge to the user
2. Start the SDK on the **main thread**.

Below is an example implementation for visionOS:

> **Note**
>
> Don't forget to replace `<APP_ID>` with your actual **Application ID**.

```swift
import UIKit
import HUMAN

@main
struct MyApp: App {

    init() {
        startHumanSDK()
    }

    func startHumanSDK() {
        do {
            let policy = HSPolicy()

            try HumanSecurity.start(appId: "<APP_ID>", policy: policy)
        }
        catch {
            print("Error: \(error)")
        }
    }
}
```

In particular, note the following:

1. **Initialization:** We start the SDK as early as possible on the main thread to ensure all URL requests include the necessary HTTP headers.
2. **Policy Configuration:** We create an `HSPolicy` instance to configure the SDK's behavior.
3. **Starting the SDK:** We call the `start` function with the following parameters:
   * Your

     Application ID

     . If you have multiple IDs, see our [guide](/applications/sdk/v5/getting-started#handle-multiple-application-ids) on how to handle them.
   * The `HSPolicy` object that we configured

## Integrate with Bot Defender

#### Send your requests through the SDK and check for a blocked request

1. Your application adds the SDK’s HTTP headers to the URL request. Include them on **every** request, and do **not** cache them. They contain a token with an expiration date, and the SDK keeps that token up to date.
2. The SDK handles the blocked request and presents a challenge to the user.
3. The challenge window affects your application. You should clean up the challenge window in case it's the last window left in the app. In the example below, we added the `onChange` on `scenePhase` environment variable to check when a window is closed. In that case, we will check if the challenge window is the only other window shown and will close it. If you have a different place in the app where you clean up, you can move the code of closing the window in case it's open there.

Below is an example implementation for visionOS:

**`Swift (challenge window)`**

```swift title="Swift (challenge window)"
import SwiftUI
import HUMAN

@main
struct MyApp: App {

    @Environment(\.scenePhase) var scenePhase
    @Environment(\.openWindow) private var openHumanChallengeWindow
    @Environment(\.dismissWindow) private var dismissHumanChallengeWindow

    init() {
        // start HUMAN...
    }

    var body: some Scene {
        // your main window and content.
        WindowGroup {
            ContentView()
        }

        // HUMAN's challenge window.
        WindowGroup(id: HSChallengeViewModel.name) {
            HSChallengeView()
        }
        .defaultSize(width: HSChallengeViewModel.width,
                     height: HSChallengeViewModel.height, depth: 0)
        .onChange(of: HSChallengeViewModel.shared.showChallenge, {
            if (HSChallengeViewModel.shared.showChallenge) {
                openHumanChallengeWindow(id: HSChallengeViewModel.name)
            }
            else {
                dismissHumanChallengeWindow(id: HSChallengeViewModel.name)
            }
        })
        .onChange(of: scenePhase) { oldPhase, newPhase in
             if (newPhase == .background && UIApplication.shared.connectedScenes.count == 2) {
                if (HSChallengeViewModel.shared.showChallenge) {
                    dismissHumanChallengeWindow(id: HSChallengeViewModel.name)
                }
            }
        }
    }
}
```

**`Swift (URLSession)`**

```swift title="Swift (URLSession)"
import HUMAN

func sendUrlRequest(url: URL) {
    var request = URLRequest(url: url)
    let myHttpHeaders = [String : String]()

    // config your request and HTTP headers...

    let humanHttpHeaders = HumanSecurity.BD.headersForURLRequest(forAppId: "<APP_ID>")
    request.allHTTPHeaderFields = myHttpHeaders.merging(humanHttpHeaders) { $1 }

    let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in
        if let data {
            let isHandled = HumanSecurity.BD.handleBlockResponse(data: data, url: url.absoluteString) { result in
                print("Challenge result = \(result)")
                // You may retry the request here.
            }
            if isHandled {
                print("Blocked response was handled by the SDK")
            }
        }
    }
    dataTask.resume()
}
```

Let's talk about what we have in the code here:

#### View (App)

1. We add the `@Environment(.openWindow)` and `@Environment(.dismissWindow)` properties and call them based on the `HSChallengeViewModel/showChallenge` observable in the SDK.
2. We add the challenge window in the `App`'s `body`.
3. We add the `@Environment(.scenePhase)` and make sure to close the challenge in case it's the last open window in the app.

#### Model/HTTP client

1. We get the SDK's HTTP headers.
2. We add those HTTP headers to our URL requests.
3. We send the URL request.
4. We send the response to the SDK. The SDK will check if it's a blocked request. If yes, it will present a challenge to the user.
5. We print the challenge result (solved/cancelled) in the completion handler.
6. We may retry the request here.

#### Handle blocked requests in your app

When the **Enforcer** blocks a request, it returns a JSON string in the response body with an HTTP status code of `403`, which includes metadata for the SDK. For example:

```json
{
  "vid": "928d7ab3-9cf1-11ee-a624-b802520f369f",
  "uuid": "fd01e6d6-9cf2-11ee-808c-acde48001122",
  "page": "...",
  "appId": "PXj9y4Q8Em",
  "action": "captcha",
  "collectorUrl": "https://collector-pxj9y4q8em.perimeterx.net"
}
```

Your app should pass the whole JSON response to the SDK via the `HSBotDefender/handleBlockResponse` function. If not, the SDK won't present a challenge to the user. When handling blocked requests:

* **Treat blocked requests as a failure.** However, if the user solves or cancels the challenge presented by the SDK, your application’s interface will be shown again. In those cases, you may need to indicate to the user that they can continue to interact with your application normally. For example, if the user was attempting to access a certain page before the challenge, then when they return to that same page after solving the challenge, you may want to show a message indicating that they can now continue on to that page.
* **Use the handler callback** to log analytics, create logs, and so on.
* **(Optional) Use the handler callback** to retry the original request when appropriate. Consider the following:
  * **Callback scope:** The callback is called out of the original request's scope. Ensure your app handles this case correctly.
  * **Challenge cancellation:** The challenge could be canceled by the user. Do not retry the request to avoid it being blocked again.
  * **Retry block possibility:** The retry attempt may also be blocked. Do not assume it will succeed.

#### Set custom parameters (optional)

[Custom parameters](/applications/set-custom-parameters) are additional custom values that you can set yourself to enrich the data you receive from HUMAN. You can have up to 10 custom parameters, and they must follow the pattern `custom_paramN`, where `N` is a number between 1 and 10. To set custom parameters, call the `HSBotDefender/setCustomParameters(parameters:forAppId:)` only **after** the `HumanSecurity/start(appId:policy:)` function has been called.

Below is an example implementation for visionOS.

```swift
import HUMAN

func setCustomParametersForBotDefender() {
    do {
        var customParameters = [String: String]()
        customParameters["custom_param1"] = "hello"
        customParameters["custom_param2"] = "world"
        try HumanSecurity.BD.setCustomParameters(parameters: customParameters, forAppId: "<APP_ID>")
    }
    catch {
        print("Error: \(error)")
    }
}
```

## Integrate with Account Defender

#### Enable Account Defender in your app

To enable Account Defender, set the `UserID` to your current logged-in user in the SDK:

```swift
import HUMAN

func onUserLoggedIn(userID: String) {
    do {
        try HumanSecurity.AD.setUserId(userId: userID, forAppId: "<APP_ID>")
    }
    catch {
        print("Error: \(error)")
    }
}
```

#### Notify HUMAN's backend on outgoing URL requests from the app

For Account Defender to protect the user’s account, your app has to provide the SDK with outgoing URL requests. While the SDK’s interceptor is enabled, the SDK collects your outgoing URL requests automatically. You do not need to manually call the SDK’s API to collect these requests.

```swift
import HUMAN

func sendUrlRequest(url: URL) {
    do {
        try HumanSecurity.AD.registerOutgoingUrlRequest(url: url.absoluteString, forAppId: "<APP_ID>")
    }
    catch {
        print("Error: \(error)")
    }

    // Send the request...
}
```

#### Set additional data (optional)

**Additional data** are additional custom values that you can set yourself to enrich the data you receive from HUMAN. Note that these are separate from [custom parameters](/applications/set-custom-parameters) and are unique to Account Defender. Additional data must follow the pattern `my_keyN`, where `N` is a number. To set additional data, use a dictionary.

Call the `HSAccountDefender/setAdditionalData(parameters:forAppId:)` only **after** the `HumanSecurity/start(appId:policy:)` function was already called.

```swift
import HUMAN

func setAdditionalDataForAccountDefender() {
    do {
        var additionalData = [String: String]()
        additionalData["my_key1"] = "hello"
        additionalData["my_key2"] = "world"
        try HumanSecurity.AD.setAdditionalData(parameters: additionalData, forAppId: "<APP_ID>")
    }
    catch {
        print("Error: \(error)")
    }
}
```