tencent cloud

WKWebView Practice
Last updated: 2025-09-05 17:52:26
WKWebView Practice
Last updated: 2025-09-05 17:52:26

Solution Description

This solution uses NSURLProtocol to intercept requests. Specific steps:
1. Register a scheme via WKWebView's Private API to ensure NSURLProtocol can intercept requests in WKWebView.
2. Create a request based on the network library type you use.
3. Load a request using WKWebView.loadRequest.

Prerequisites

Sample Code

Note:
This documentation provides a reference solution for HTTPDNS integration in WebView scenarios. The example code is not official code for online production environments. Before integration, we recommend that you fully evaluate the content of this documentation to ensure the robustness of the solution meets your production standards.
If you need to refer to an example, you can refer to the source code of MSDKDnsHttpMessageTools and modify or reuse it based on business needs.
The complete example code is in WebViewController.m of the Demo.
// 1. Register NSURLProtocol to intercept requests
[NSURLProtocol registerClass:[MSDKDnsHttpMessageTools class]];

// 2. Register scheme
Class cls = NSClassFromString(@"WKBrowsingContextController");
SEL sel = NSSelectorFromString(@"registerSchemeForCustomProtocol:");
if ([cls respondsToSelector:sel]) {
// Requests via http and https, likewise via other schemes but must meet the URL Loading System
[cls performSelector:sel withObject:@"http"];
[cls performSelector:sel withObject:@"https"];
}

// 3. Use WKWebView.loadRequest
[self.wkWebView loadRequest:request];


Was this page helpful?
You can also Contact Sales or Submit a Ticket for help.
Yes
No

Feedback