URLSession integration
How to use the DataDome SDK with URLSession
For each request to protect with DataDome, use the following methods to create the data task
func protectedDataTask(with url: URL,
captchaDelegate: CaptchaDelegate?,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void)
-> URLSessionDataTask
func protectedDataTask(with request: URLSessionRequest,
captchaDelegate: CaptchaDelegate?,
completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void)
-> URLSessionDataTask
We also provide async version of those methods if you are using Swift Concurency :
func protectedDataTask(withURL url: URL, captchaDelegate: CaptchaDelegate?) async throws -> (Data, URLResponse)
func protectedDataTask(withRequest request: URLRequest, captchaDelegate: CaptchaDelegate?) async throws -> (Data, URLResponse)
Only the URLSessionDataTasks
created by the above two methods are monitored and protected by DataDome.
Here a sample code to create and execute a data task
import DataDomeSDK
guard let url = URL(string: "https://datadome.co") else {
return
}
let task = URLSession.shared.protectedDataTask(with: url, captchaDelegate: self, completionHandler: { _, _, _ in
print("Request completed")
})
task.resume()
To manually manage the presentation of the captcha view controller, implement the CaptchaDelegate
protocol
extension MyViewController: CaptchaDelegate {
func present(captchaController controller: UIViewController) {
self.navigationController?.present(controller, animated: true, completion: nil)
}
func dismiss(captchaController controller: UIViewController) {
controller.dismiss(animated: true, completion: nil)
}
}
Alternatively, you can pass nil
to the captchaDelegate, the SDK will automatically manage navigation for you and will display the CaptchaViewController
modally on top of the visible view controller.
SFCC and redirection policy
When calling an SFCC endpoint, the captcha will be displayed according to different rules.
You will need to implement this method from the URLSessionTaskDelegate
:
urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void)
And return nil
if the URL inside the Location
HTTP header has a path containing DDUser-Challenge
as one of its components.
Example:
func urlSession(_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void) {
if let location = response.value(forHTTPHeaderField: "location"),
let url = URL(string: location),
url.pathComponents.contains("DDUser-Challenge") {
return completionHandler(nil)
}
return completionHandler(request)
}
You will also have to set DataDomeSDK.bypassHTTPAccept = true
to display the captcha correctly.
Updated 6 months ago