Combine Integration

How to use the DataDome SDK with Combine & URLSession.DataTaskPublisher

VersionVersion LicenseLicense PlatformPlatform

If you are using Combine and DataTaskPublisher to perform networking requests in your app, we have you covered.
Use the following apis to create a DataTaskPublisher with the DataDome operators

/// Provides a publisher with downstream DataDome operators
/// - Parameters:
///   - url: The url to be requested
///   - captchaDelegate: The captcha delegate
/// - Returns: A publisher with the DataDome operators
func protectedDataTaskPublisher(forURL url: URL,
                                captchaDelegate: CaptchaDelegate?)
    -> AnyPublisher<URLSession.DataTaskPublisher.Output, URLSession.DataTaskPublisher.Failure>

Or by using an URLRequest instance as parameter

/// Provides a publisher with downstream DataDome operators
/// - Parameters:
///   - request: The request to be processed
///   - captchaDelegate: The captcha delegate
/// - Returns: A publisher with the DataDome operators
func protectedDataTaskPublisher(forRequest request: URLRequest,
                                captchaDelegate: CaptchaDelegate?)
-> AnyPublisher<URLSession.DataTaskPublisher.Output, URLSession.DataTaskPublisher.Failure>

Here an example on how to use the DataDome protected publisher

import DataDomeSDK

URLSession
.shared
.protectedDataTaskPublisher(forURL: url, captchaDelegate: nil)
.sink(receiveCompletion: { completion in
      switch completion {
        case .finished:
            break
        case .failure(let error):
            print(error.localizedDescription)
      }
}, receiveValue: { response in
     guard let httpResponse = response.response as? HTTPURLResponse else {
       print("Invalid response")
       return
     }

     print("Did receive response with code \(httpResponse.statusCode)")
  }
})

You can use any other operators to validate or transform the publisher or part of its elements. For more details, please visit Apple Documentation

You can also implement the CaptchaDelegate protocol to manage the navigation of the CaptchaViewController

import DataDomeSDK

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)
    }
}