All Products
Search
Document Center

Captcha:Use WKWebView to integrate CAPTCHA 2.0 into an iOS application based on Swift

Last Updated:Aug 16, 2024

As the development technology of hybrid applications becomes more sophisticated, you can integrate mobile HTML5-based CAPTCHA 2.0 into an iOS application by using the WKWebView component to achieve anti-bot protection for the application. This topic describes how to integrate CAPTCHA 2.0 into an iOS application.

Background information

Mobile HTML5-based CAPTCHA 2.0 offers the advantages of rapid iteration and strong compatibility. By integrating mobile HTML5-based CAPTCHA 2.0 into an application, you no longer need to worry about the compatibility issues that may be caused by various dependencies and references in the native application components. Thanks to the rapid iteration of mobile HTML5-based CAPTCHA 2.0, you can better protect your application against strong adversarial attacks.

Procedure

To integrate HTML5-based CAPTCHA 2.0 into an iOS application, perform the following steps:

  1. Integrate CAPTCHA 2.0 into the HTML5 page client.

  2. Integrate a CAPTCHA 2.0 server SDK into the business server of the HTML5 page client, and then call the VerifyIntelligentCaptcha operation on the business server to initiate a verification request.

  3. Use the WKWebView component to load and deploy the business page on which you want to call CAPTCHA 2.0 on an iOS application.

If you have questions when you use CAPTCHA 2.0, submit a ticket for technical support.

Prerequisites

  • CAPTCHA 2.0 is activated, and a verification scenario whose Client Type is set to App(Webview+H5) is created. For more information, see the Step 2: Create a verification scenario section of the "Integration guide" topic.

  • An iOS application that runs 10.0 or later is installed.

Step 1: Integrate CAPTCHA 2.0 into the HTML5 page client

  1. Integrate the client code provided by CAPTCHA 2.0 into the code of the HTML5 page client. For more information, see Integrate CAPTCHA 2.0 into a business client.

  2. Modify the client integration code based on the environment in which the business result verification is performed.

    • If the business result verification is performed on the iOS application, you must modify the following code:

      1. Add the corresponding JavaScript function to the callback function for the business request to call the method that is used to implement interaction between JavaScript and WKWebView based on the WkScriptMessageHandler protocol. Then, the verification result is returned. For more information about the method, see Substep 3 and Substep 4 in the "Step 3: Load and deploy the HTML5 business page on the iOS application" section of this topic. After the verification result is returned, you can perform different business operations on the iOS application.

        // The callback function for the business request with CAPTCHA verification.
        async function captchaVerifyCallback(captchaVerifyParam) {
          // 1. Initiate a business request to the backend. Then, both the CAPTCHA verification result and the business result are returned.
          const result = await xxxx('http:// The URL of your business request', {
              captchaVerifyParam: captchaVerifyParam, // The CAPTCHA parameter.
              yourBizParam... // The business parameter.
          });
        
          // 2. Construct standard response parameters.
          const verifyResult = {
            captchaResult: result.captchaVerifyResult, // Required. Indicates whether the CAPTCHA verification is passed. The value is of the BOOLEAN type.
            bizResult: returns the business verification result, // Optional. Indicates whether the business verification is passed. The value is of the BOOLEAN type. If no business verification scenario is involved, the bizResult parameter is left empty.
          };
          // Call the JavaScript method that is implemented by using the WkScriptMessageHandler protocol to obtain the verification result.
          window.webkit && window.webkit.messageHandlers.getVerifyData.postMessage(verifyResult)
          return verifyResult;
        }
      2. Define the callback function for the business request verification result of the HTML5 page as an empty function. This operation migrates business operations from the HTML5 page to the iOS application.

        // The callback function for the business request verification result.
        function onBizResultCallback(bizResult) {
          // Define the function as an empty function.
        }
    • If the business result verification is performed on the HTML5 page, you do not need to modify the code.

    • If the business result verification is performed on both the HTML5 page and the iOS application, you must modify the following code. This enables the HTML5 page and iOS application to use the same set of integration code but independent business result verification logic.

      1. Add the corresponding JavaScript function to the callback function for the business request. For more information, see Substep i in the "Step 1: Integrate CAPTCHA 2.0 into the HTML5 page client" section of this topic.

      2. Modify the callback function for the business request verification result of the HTML5 page to check whether the verification is performed on the HTML5 page. If the verification is performed on the HTML5 page, add the business logic of the HTML5 page.

        // The callback function for the business request verification result.
        function onBizResultCallback(bizResult) {
          // Check whether the business result verification is performed on the iOS application. If the custom JavaScript function is not involved in the verification environment, the business result verification is performed on the HTML5 page.
          // You can also use a custom condition to distinguish between the two environments.
          if (!window.webkit || !window.webkit.messageHandlers) {
              // The business logic of the HTML5 page.
          }
        }

Step 2: Integrate CAPTCHA 2.0 into the business server of the HTML5 page client

Integrate a CAPTCHA 2.0 server SDK into the business server of the HTML5 page client, and then call the VerifyIntelligentCaptcha operation to initiate a verification request. For more information, see Integrate CAPTCHA 2.0 into a business server.

Important

After you complete server integration, make sure that CAPTCHA 2.0 is integrated into the business client and business server. For more information, see the Step 3: Integrate CAPTCHA 2.0 section of the "Integration guide" topic.

Step 3: Load and deploy the HTML5 business page on the iOS application

  1. Import the relevant dependencies to the Controller.swift file of your iOS application project.

    import SwiftUI
    import WebKit
  2. Load the HTML5 business page into the Controller.swift file of your iOS application project.

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(webView)
        let url = URL(string: "http://x.x.x.x/demo/")
        let request = URLRequest(url: url!);
        webView.load(request); // Load the page.
    }
  3. Configure a WKWebView object and implement the interaction between JavaScript and WKWebView by using the WKScriptMessageHandler protocol.

    lazy var webView: WKWebView = {
        // Enable adaptive scaling for the page.
        let javascript = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta)";
        let configuration = WKWebViewConfiguration();
        let userScript = WKUserScript(source: javascript, injectionTime: .atDocumentEnd, forMainFrameOnly: true);
        let usercontroller = WKUserContentController();
        usercontroller.addUserScript(userScript);
        configuration.userContentController = usercontroller;
        // Add a method to call the JavaScript function on the HTML5 page. You can modify the method name based on your business requirements.
        configuration.userContentController.add(self, name: "getVerifyResult");
        // Configure the WKWebView object.
        let webView = WKWebView(frame: self.view.frame, configuration: configuration);
        webView.navigationDelegate = self;
        return webView;
    }()
  4. Configure a corresponding method of the WKScriptMessageHandler protocol to obtain the return value of CAPTCHA 2.0 and your business logic code, and return the verification result to the custom operation.

    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if(messsage.name == "getVerifyResult"){
            // After the verification result is returned, you can perform different business operations.
            print(message.body)
        }
    }