iOS + URLSession

How to use the DataDome SDK with URLSession

📘

Using DataDomeSDK 3.x?

This page covers a new integration of DataDomeURLSession. To upgrade an app that uses DataDomeSDK 3.x, follow the migration guide. The DataDomeSDK 3.x documentation is on the v3 page.

DataDomeURLSession handles DataDome responses for the calls your app sends with URLSession to endpoints protected by DataDome. It is built on top of the CoreDataDome SDK: every response is checked, challenges are displayed automatically, and the request is retried once the challenge is resolved.

Requirements

  • iOS 15+
  • Xcode 26+, which Apple requires for App Store Connect uploads since April 28, 2026
  • Swift Package Manager only
  • A DataDome client-side key, available in your DataDome dashboard

Add the package

With Xcode

  1. In Xcode, open File ▸ Add Package Dependencies….
  2. Enter the package URL.

    https://github.com/DataDome/datadome-urlsession-package.git
  3. Set the dependency rule to Up to Next Major Version starting at 1.0.0.
  4. Add the DataDomeURLSession library product to your application target.

CoreDataDome is added automatically as a dependency.

With a Package.swift manifest

dependencies: [
    .package(url: "https://github.com/DataDome/datadome-urlsession-package.git", from: "1.0.0")
],
targets: [
    .target(
        name: "YourApp",
        dependencies: [
            .product(name: "DataDomeURLSession", package: "mobile-sdk-ios-wrapper-urlsession")
        ]
    )
]

Configure your DataDome client-side key

You can provide your client-side key either programmatically or through your app's Info.plist.

Create the DataDome instance once and reuse it for the lifetime of your app, for example as a property of a shared networking object. It is an actor and is safe to share across tasks.

Option A: Programmatic

import CoreDataDome

let configuration = DataDomeConfiguration(clientKey: "YOUR_DATADOME_CLIENT_SIDE_KEY")
let dataDome = DataDome(configuration: configuration)

You can optionally pass your protected domain:

let configuration = DataDomeConfiguration(
    clientKey: "YOUR_DATADOME_CLIENT_SIDE_KEY",
    clientDomain: URL(string: "https://your-domain.com")
)

Option B: Info.plist

Add a DataDome dictionary to your Info.plist:

<key>DataDome</key>
<dict>
    <key>ClientSideKey</key>
    <string>YOUR_DATADOME_CLIENT_SIDE_KEY</string>
    <!-- Optional -->
    <key>Domain</key>
    <string>https://your-domain.com</string>
</dict>

Then build the configuration from the bundle:

import CoreDataDome

let configuration = try DataDomeConfiguration.configurationFromBundle()
let dataDome = DataDome(configuration: configuration)

DataDomeConfiguration.configurationFromBundle() throws if the DataDome dictionary or its ClientSideKey entry is missing. Handle the error, or use the programmatic initializer instead.

Send requests to protected endpoints

Send every call to an endpoint protected by DataDome through a ProtectedURLSession. It wraps a URLSession and mirrors its API.

import CoreDataDome
import DataDomeURLSession

// Wraps URLSession.shared
let session = ProtectedURLSession(dataDome: dataDome)

// Wraps your own URLSession
let session = ProtectedURLSession(dataDome: dataDome, session: mySession)

// Same as above
let session = mySession.protected(by: dataDome)

protected(by:) returns a lightweight wrapper over the same session, so you can call it for each request.

Every call to an endpoint protected by DataDome must be sent through ProtectedURLSession. For requests sent directly on the underlying URLSession, DataDome responses are ignored: challenges are skipped and the request completes without retry.

async/await

let (data, response) = try await session.data(for: request)
let (uploadData, uploadResponse) = try await session.upload(for: request, from: body)
let (fileUploadData, fileUploadResponse) = try await session.upload(for: request, fromFile: fileURL)
let (location, downloadResponse) = try await session.download(for: request)
let (bytes, bytesResponse) = try await session.bytes(for: request)

Each method also accepts a URL instead of a URLRequest (except upload), and an optional delegate: parameter, as in URLSession. The delegate receives the callbacks of every request sent, retries included.

With download, your app owns the returned file: move or delete it once you have read it. Files downloaded by attempts that were retried or blocked are deleted by the SDK.

Completion handlers

let task = session.dataTask(with: request) { data, response, error in
    // Called on an arbitrary thread
}
task.resume()

uploadTask(with:from:completionHandler:) and downloadTask(with:completionHandler:) work the same way. They return a ProtectedURLSessionTask, which you resume() or cancel(). A cancelled task calls its completion handler with URLError(.cancelled).

With downloadTask, the downloaded file is deleted once the completion handler returns: move it inside the handler if you need to keep it.

Combine

session.dataTaskPublisher(for: request)
    .sink(receiveCompletion: { completion in
        if case let .failure(error) = completion {
            print(error.localizedDescription)
        }
    }, receiveValue: { data, response in
        // Handle the response
    })
    .store(in: &cancellables)

The publisher fails with any Error, so that it can report a DataDomeError. Cancelling the subscription cancels the request.

Example

import Foundation
import CoreDataDome
import DataDomeURLSession

final class NetworkManager: Sendable {
    static let shared = NetworkManager()

    private let dataDome: DataDome
    private let session: ProtectedURLSession

    private init() {
        let configuration = DataDomeConfiguration(clientKey: "YOUR_DATADOME_CLIENT_SIDE_KEY")
        dataDome = DataDome(configuration: configuration)
        session = URLSession.shared.protected(by: dataDome)
    }

    func protectedData(from url: URL) async throws -> (Data, HTTPURLResponse?) {
        let (data, response) = try await session.data(for: URLRequest(url: url))
        return (data, response as? HTTPURLResponse)
    }
}

How challenges are handled

Every response is checked by DataDome, whatever its status code. The SDK displays the challenge and block pages, handling all presentation automatically.

DataDome outcomeResult
No challengeThe response is returned unchanged.
Challenge resolved by the end userThe request is sent again automatically with the new DataDome cookie, and the response of the retry is returned.
Challenge resolved, after a redirectThe retry goes to the redirect destination, with the request URLSession sent there (for example a GET after a 303), so the original request is not sent twice.
Challenge dismissed by the end userThe original response is returned.
Block pageThrows DataDomeError.blocked.
Challenge resolved, but the body is an httpBodyStreamThrows DataDomeError.cannotRetryStreamBody: the stream was already read. The DataDome cookie is set, so resend the request with a new body stream, or use httpBody or an upload method so the SDK can retry it.
Request cancelledThrows URLError(.cancelled).

Handle these errors like any other networking error:

do {
    let (data, response) = try await session.data(for: request)
    // Handle the response
} catch DataDomeError.blocked {
    // The user is blocked: the request cannot proceed
} catch DataDomeError.cannotRetryStreamBody {
    // Resend the request with a new body stream
} catch {
    // Other networking errors
}

With completion handlers, errors are passed as the error parameter. With Combine, they are sent as a .failure completion.

Customizing the session

You can wrap your own URLSession and URLSessionConfiguration. If you do, keep the cookie handling enabled so the DataDome cookie set after a resolved challenge is attached to the retried request:

  • Leave configuration.httpShouldSetCookies = true (the default).
  • Keep the shared HTTPCookieStorage (configuration.httpCookieStorage = .shared, the default), or use a custom storage as described below.

If the DataDome cookie is absent, the request is challenged again in a loop.

Use a custom cookie storage

CoreDataDome 1.1.0+ lets you keep the DataDome cookie in a storage other than HTTPCookieStorage.shared, such as a shared container. Pass the same HTTPCookieStorage instance to both DataDomeConfiguration and the URLSessionConfiguration you wrap:

import CoreDataDome
import DataDomeURLSession

let cookieStorage = HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier: "group.com.example.app")

let dataDomeConfiguration = DataDomeConfiguration(
    clientKey: "YOUR_DATADOME_CLIENT_SIDE_KEY",
    cookieStorage: cookieStorage
)
let dataDome = DataDome(configuration: dataDomeConfiguration)

let sessionConfiguration = URLSessionConfiguration.default
sessionConfiguration.httpCookieStorage = cookieStorage
let session = URLSession(configuration: sessionConfiguration).protected(by: dataDome)

If the two storages differ, the DataDome cookie is written to a storage the session never reads from, and every request is challenged again.

An ephemeral session also works, as long as you use the same URLSessionConfiguration instance on both sides: URLSessionConfiguration.ephemeral returns a new configuration, with a new storage, each time you access it. Its storage is kept in memory only, so the DataDome cookie is lost when the session goes away, and the next launch starts with a new challenge.

Configure how challenges are displayed

CoreDataDome 1.1.0+ lets you change how challenges are displayed with a DataDomeChallengeDisplayConfiguration:

let dataDomeConfiguration = DataDomeConfiguration(
    clientKey: "YOUR_DATADOME_CLIENT_SIDE_KEY",
    challengeDisplayConfiguration: DataDomeChallengeDisplayConfiguration(
        isDismissible: true,
        windowLevel: DataDomeChallengeDisplayConfiguration.defaultWindowLevel
    )
)
ParameterDefaultDescription
isDismissiblefalseWhether you can close a challenge without resolving it. The original response is then returned and the request completes without retry. Invisible challenges show nothing to close.
windowLevelUIWindow.Level.alert + 1The level of the window challenges are displayed in. Raise it if your app displays its own windows above the alert level. System windows, such as permission prompts, always remain visible.

Cookies

The DataDome cookie is stored in the cookie storage of your configuration, HTTPCookieStorage.shared by default. DataDome is an actor, so its cookie methods must be awaited.

To share the DataDome cookie with a WKWebView:

if let cookie = await dataDome.getCookie(forURL: url) {
    await webView.configuration.websiteDataStore.httpCookieStore.setCookie(cookie)
}

To set a DataDome cookie obtained elsewhere, for example from a web view:

await dataDome.setCookie(cookie)

To clear the DataDome cookie:

await dataDome.unsafeClearCachedData()

Do not add the DataDome cookie to your requests manually. For more details, see iOS cookies.

Troubleshooting

SymptomResolution
No such module 'CoreDataDome'Make sure the DataDomeURLSession product is added to your app target so SPM resolves CoreDataDome as a dependency.
Build error: "requires minimum platform version 15.0"Raise your app target's Minimum Deployments to iOS 15.0+.
configurationFromBundle() throws on launchThe DataDome dictionary or its ClientSideKey entry is missing from Info.plist. Add it, or use the programmatic DataDomeConfiguration(clientKey:) initializer.
Requests are challenged, but no challenge is displayedThe request was sent on a plain URLSession. Send it through a ProtectedURLSession.
The request is challenged again in a loopThe DataDome cookie is absent from the request. Keep httpShouldSetCookies = true and make sure the session uses the same cookie storage as DataDomeConfiguration.
DataDomeError.cannotRetryStreamBody is thrownThe request body is an httpBodyStream, which cannot be read twice. Resend the request with a new stream, or use httpBody or an upload method.

Did this page help you?