The translation was generated automatically and may contain mistakes

Install and connect VK ID Captcha SDK iOS

This instruction describes how to install and connect the Captcha SDK VK ID for the iOS platform, as well as how to configure the captcha display and results processing.

Before starting work, get acquainted with interaction scenario with VK ID Captcha and software requirements.

Then integrate VK ID Captcha SDK iOS:

  1. 1.
  2. 2.
  3. 3.
  4. 4.

Software requirements

Software
Version
iOS
12 or later
Swift Package Manager
5.9 or newer
Xcode
16.2 or later
CocoaPods
1.13 or later

Step 1. Installation

You can install the library.. VKCaptchaSDK Using one of the dependency managers: Swift Package Manager or CocoaPods .

Swift Package Manager

  1. 1.

    Add a library VKCaptchaSDK Depending on your Package.swift :

    Swift
    dependencies: [ .package(url: "https://github.com/VKCOM/vkid-captcha-ios-sdk", .upToNextMajor(from: "0.1.0")) ]
  2. 2.

    Download and unzip the zip file: https://artifactory-external.vkpartner.ru/artifactory/vk-id-captcha/ios/VKCaptchaSDK-0.1.0.zip .

  3. 3.

    Add a unpacked file to your project VKCaptchaSDKResources.bundle .

CocoaPods

  1. 1.

    Add a library VKCaptchaSDK in your Podfile :

    Ruby
    source 'https://github.com/VKCOM/vkid-captcha-ios-sdk.git' pod 'VKCaptchaSDK', '~> 0.1.0'
  2. 2.

    Run the command to set dependencies:

    Ruby
    pod install --repo-update

Step 2. Connection

After installation Library VKCaptchaSDK :

  1. 1.

    Import the Library VKCaptchaSDK Where you will work with Captcha:

    Swift
    import VKCaptchaSDK
  2. 2.

    Initialize the class VKCaptchaHandler and its copy:

    Swift
    let configuration = VKCaptchaHandler()

Step 3. Captcha display

Display the captcha popup in one of three ways:

Important! Call methods handleCaptcha() , getCaptchaViewController() , openCaptcha() Only in the stream MainThread .

handleCaptcha() (recommended)

Method handleCaptcha() checks the response from the API VKontakte and displays the captcha if necessary.

You can display the captcha in one of the following ways:

  • •
    Use the class VKCaptchaNewUIWindowPresenter() (by default) if you need to display the captcha on the new application screen.
  • •
    Use the class VKCaptchaPresenterDefault() if you need to display the captcha on the same application screen from which the user initiated his action.
  • •
    Create your own class that supports the protocol VKCaptchaPresenter - may be needed if you need your own captcha logic.

See also an example of captcha processing for URLSession .

When used VKCaptchaNewUIWindowPresenter() The captcha will appear on the new screen UIWindow .

**Пример кода с VKCaptchaNewUIWindowPresenter() **

Swift
captchaHandler.handleCaptcha( from: data, // ответ сервера responseHeaders: headers, // заголовки ответа от сервера domain: domain, // домен, для которого выполнен запрос with: VKCaptchaNewUIWindowPresenter(), // отображение капчи completion: { result in    switch result { case .success(let token): // логика работы при наличии токена успешного прохождения капчи case .failure(let error): // логика работы при ошибке } } )

Using the class VKCaptchaPresenterDefault() pass a controller in it that will display the captcha window.

**Пример кода с VKCaptchaPresenterDefault() **

Swift
let presenter = VKCaptchaPresenterDefault(presentingViewController: self) captchaHandler.handleCaptcha( from: data, // ответ сервера   responseHeaders: headers, // заголовки ответа от сервера domain: domain, // домен, для которого выполнен запрос with: presenter, // отображение капчи completion: { result in    switch result { case .success(let token): // логика работы при наличии токена успешного прохождения капчи case .failure(let error): // логика работы при ошибке } } )

getCaptchaViewController()

Get a captcha window with the method getCaptchaViewController() and display it. To get the data to display, use the method handleCaptchaData() .

**Пример кода с getCaptchaViewController() **

Swift
let controller = captchaHandler.getCaptchaViewController(    captchaData: captchaData, // данные для отображения капчи, полученные методом handleCaptchaData() completion: { result in             switch result { case .success(let token): // логика работы при наличии токена успешного прохождения капчи case .failure(let error): logError(.captcha, error.localizedDescription) // логика работы при ошибке } }) present(controller, animated: true)

openCaptcha()

Using this method, the captcha window will be displayed using the protocol VKCaptchaPresenter . To get the data to display, use the method handleCaptchaData() .

**Пример кода с openCaptcha() **

Swift
let controller = captchaHandler.openCaptcha(    captchaData: captchaData, // данные для отображения капчи, полученные методом handleCaptchaData() presenter: VKCaptchaNewUIWindowPresenter(), // отображение капчи     completion: { result in             switch result { case .success(let token): // логика работы при наличии токена успешного прохождения капчи case .failure(let error): logError(.captcha, error.localizedDescription) // логика работы при ошибке } }) present(controller, animated: true)

Obtaining captcha data with handleCaptchaData()

To get the captcha data, use the method handleCaptchaData() . 

**Пример кода с  handleCaptchaData() **

Swift
let result = captchaHandler.handleCaptchaData( from: data, // ответ сервера  responseHeaders: headers, // заголовки ответа от сервера domain: domain, // домен, для которого выполнен запрос ) if case .failure(.noCaptcha) = result { // логика обработки ответа сервера } else if case .success(let captchaData) = result { // логика отображения капчи с предоставленными данными } else if case .failure(let error) = result { // ошибка анализа ответа сервера

Step 4. Adding a token to the request to the API VKontakte

If you successfully pass the captcha, you will receive a token VKCaptchaToken .

The token can be of two types, each of which has its own version of adding a token to the request:

  • •
    domain Method addDomainCaptcha() .
  • •
    default Method addDefaultCaptcha() .

To add a token to a request, call addCaptchaToken with parameter VKCaptchaToken .

If you get an error AddingCaptchaTokenError , the token could not be added. Check the request and try again.

**Example of adding tokens to a request for URLRequest **

Swift
urlRequest.addCaptchaToken(token: token)
Swift
extension URLRequest { public enum AddingCaptchaTokenError: Error { case urlError } public mutating func addCaptchaToken(token: VKCaptchaToken) throws { switch token.type { case .domain: addDomainCaptcha(token: token.value) case .default: try addDefaultCaptcha(token: token.value) } } public mutating func addDomainCaptcha(token: String) { setValue(token, forHTTPHeaderField: VKCaptchaConstants.domainCaptchaHeaderName) } public mutating func addDefaultCaptcha(token: String) throws { guard let url else { throw AddingCaptchaTokenError.urlError } var components = URLComponents(url: url, resolvingAgainstBaseURL: false) components?.queryItems?.append( .init(name: VKCaptchaConstants.defaultCaptchaParamName, value: token) ) self.url = components?.url } }

An example of captcha processing for URLSession

Swift
let urlSession = URLSession() let captchaHandler = VKCaptchaHandler() private func execute( _ urlRequest: URLRequest ) { let task = self.urlSession.dataTask( with: urlRequest ) { data, response, error in let domain: String if #available(iOS 16.0, *) { domain = urlRequest.url?.host() ?? "" } else { domain = urlRequest.url?.host ?? "" } DispatchQueue.main.async { captchaHandler.handleCaptcha( from: data, // ответ сервера responseHeaders: (response as? HTTPURLResponse)?.allHeaderFields, // заголовки, полученные в ответе от сервера domain: domain // домен, на котором выполнялся запрос ) { result in if case .failure(.noCaptcha) = result { // обработка ответа от сервера } else if case .success(let captchaToken) = result { var newRequest = urlRequest do{ try newRequest.addCaptchaToken(token: captchaToken) // повторное выполнение запроса } catch let error as URLRequest.AddingCaptchaTokenError { // обработка ошибки добавления токена капчи } } else if case .failure(let error) = result { // обработка ошибки капчи } } } } task.resume() }

Classes, Methods, Protocols (Handbook)

  • •
    VKCaptchaHandler Primary Class for Work:
    • •
      VKCaptchaHandler.handleCaptcha() — complete captcha processing: server response analysis, captcha display, analysis and display of the result.
    • •
      VKCaptchaHandler.handleCaptchaData() — captcha data acquisition .
    • •
      VKCaptchaHandler.openCaptcha() Captcha display.
    • •
      VKCaptchaHandler.getCaptchaViewController() Getting a captcha window.
    • •
      getDomainToken() Method of obtaining domain token for a specific domain.
  • •
    VKCaptchaPresenter protocol for displaying captchas.
  • •
    VKCaptchaData Captcha display data.
  • •
    VKCaptchaType Type of captcha. There may be two types: domain , default .
  • •
    VKCaptchaToken The result of the captcha. There may be two types: domain , default .
  • •
    VKCaptchaConstants constants needed to work with captchas.
  • •
    CaptchaHandlingError — captcha errors .

VKCaptchaHandler

VKCaptchaHandler - the main class for work with captcha.

Class diagram

Swift
public final class VKCaptchaHandler { func handleCaptcha( from response: Data?, // ответ сервера responseHeaders: [AnyHashable: Any]?, // заголовки ответа от сервера domain: String, // домен, для которого выполнен запрос with presenter: VKCaptchaPresenter = VKCaptchaNewUIWindowPresenter(), // отображение капчи completion: @escaping (Result<VKCaptchaToken, CaptchaHandlingError>) -> Void // логика работы при наличии токена и при отсутствии ) func handleCaptchaData( from response: Data?, // ответ сервера responseHeaders: [AnyHashable: Any]?, // заголовки ответа от сервера domain: String // домен, для которого выполнен запрос ) -> Result<VKCaptchaData, CaptchaHandlingError> // логика обработки ответа сервера и отображения капчи func openCaptcha( captchaData: VKCaptchaData, // данные для отображения капчи, полученные методом handleCaptchaData() presenter: VKCaptchaPresenter = VKCaptchaNewUIWindowPresenter(), // отображение капчи completion: @escaping (Result<VKCaptchaToken, CaptchaHandlingError>) -> Void // логика работы ) func getCaptchaViewController( captchaData: VKCaptchaData, // данные для отображения капчи, полученные методом handleCaptchaData() completion: @escaping (Result<VKCaptchaToken, CaptchaHandlingError>) -> Void // логика работы ) -> UIViewController? static func getDomainToken(for domain: String) -> VKCaptchaToken? // метод получения domain токена для определенного домена. }

VKCaptchaPresenter

VKCaptchaPresenter A protocol for displaying captchas. Implementation of the Protocol VKCaptchaPresenter The default class is VKCaptchaNewUIWindowPresenter .

You can also use the class. VKCaptchaPresenterDefault() if you want to display a captcha on the same application screen from which the user initiated their action, or create your own class that supports the protocol VKCaptchaPresenter if you want your own captcha logic.

Mistakes

In the event of an error in the field error The following values can be returned CaptchaHandlingError :

  • •
    failedToCreateCaptchaData failed to generate data to display the captcha.
  • •
    noCaptcha There is no captcha error in the server response.
  • •
    captchaError(Error) — you can specify a value in a nested error Error к типу VKCaptchaResultError to get a captcha pass error:
    • •
      VKCaptchaResultError.cancel The user closed the captcha window.
    • •
      VKCaptchaResultError.unknown Unknown error.
    • •
      System error.