All Products
Search
Document Center

HTTPDNS:Use HTTPDNS in WebView scenarios on iOS

Last Updated:Dec 17, 2025

Important

This document describes how to use IP addresses resolved by HTTPDNS in WKWebView scenarios. For more information about the HTTPDNS resolution service, see the or the iOS SDK Integration Manual.

1. Introduction

In Use HTTPDNS in native scenarios on iOS, you learned how to use HTTPDNS in native scenarios on the iOS platform to implement anti-hijacking, precise scheduling, and instant DNS resolution.

WKWebView is another scenario on iOS that frequently involves network requests. WKWebView is a modern web view provided by the WebKit framework for displaying web content in iOS applications. It replaces the legacy UIWebView and provides better performance, more features, and higher security. Using HTTPDNS when WKWebView loads web pages can improve network security and performance.

2. Current technology

As the iOS system evolves, technical solutions for integrating HTTPDNS with WKWebView are also evolving:

  • Before iOS 17.0: Apple did not provide official hook interfaces for DNS resolution in WKWebView. It also did not directly provide interfaces for custom network request implementations. This required complex solutions that intercepted traffic by hooking private APIs.

  • iOS 17.0 and later: Apple introduced the ProxyConfiguration API. This API provides official proxy configuration capabilities for WKWebView. It lets you reliably intercept all network requests, making it possible to seamlessly integrate HTTPDNS.

According to official Apple statistics (as of June 4, 2025), iOS 17 and later is installed on over 85% of all iPhone devices, and this number is growing. HTTPDNS provides non-functional improvements for WKWebView scenarios, such as anti-hijacking, precise scheduling, and instant resolution. Therefore, we recommend using this solution to integrate HTTPDNS. This approach covers most customers. Users on older system versions will gradually gain this capability as they upgrade.

3. Recommended solution: Local proxy-based solution for iOS 17+

3.1 Solution overview

iOS 17.0 introduced the ProxyConfiguration API, which allows applications to configure a local proxy server for WKWebView. This method starts a local proxy server that intercepts all network requests from WKWebView. At the proxy layer, the server performs HTTPDNS domain name resolution and then forwards the requests to the real server.

image

Compared with traditional technical solutions, the local proxy solution has the following significant advantages:

  1. Stability: This solution is based on the official API for iOS 17 and later. It does not rely on private APIs or obfuscation techniques, which provides the best stability and compatibility.

  2. Applicability: The solution is completely transparent to the WebView. You do not need to handle complex details such as cookies, redirection, or Cross-Origin Resource Sharing (CORS). It supports all protocols, such as HTTP, HTTPS, and WebSocket, which provides broad coverage.

  3. Security: The local proxy is isolated within the app sandbox. It is not exposed externally and has no exploitable attack surface.

  4. High performance: This is a purely local implementation. All network data is copied only once at the memory level. The performance overhead on the client is negligible.

  5. Easy maintenance: The implementation logic is clear, and the maintenance cost is relatively low.

3.2 Integration reference

Creating a local proxy service, parsing HTTP requests, creating connections based on HTTPDNS resolution results, and forwarding data require significant implementation effort. We have open-sourced an implementation on GitHub and released it as an SDK: Open-source repository. You can adjust this implementation as needed to better suit your business requirements.

3.2.1 Cocoapods integration

Add the EMASLocalProxy dependency to your Podfile:

source 'https://github.com/aliyun/aliyun-specs.git'

target 'yourAppTarget' do
    use_framework!
    
    pod 'AlicloudHTTPDNS', 'x.x.x'
    pod 'EMASLocalProxy', 'x.x.x'
end

3.2.2 Usage example

After integration, you can configure WKWebView during initialization as follows:

#import <EMASLocalProxy/EMASLocalProxy.h>
#import <AlicloudHttpDNS/AlicloudHttpDNS.h>

// Create a WKWebViewConfiguration
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];

// Configure the DNS resolver
[EMASLocalHttpProxy setDNSResolverBlock:^NSArray<NSString *> *(NSString *hostname) {
    // Get the HTTPDNS service instance
    HttpDnsService *httpdns = [HttpDnsService sharedInstance];
    HttpdnsResult *result = [httpdns resolveHostSyncNonBlocking:hostname byIpType:HttpdnsQueryIPTypeBoth];

    if (result && (result.hasIpv4Address || result.hasIpv6Address)) {
        NSMutableArray<NSString *> *allIPs = [NSMutableArray array];
        if (result.hasIpv4Address) {
            [allIPs addObjectsFromArray:result.ips];
        }
        if (result.hasIpv6Address) {
            [allIPs addObjectsFromArray:result.ipv6s];
        }
        NSLog(@"HTTPDNS resolution successful. Domain name: %@, IP: %@", hostname, allIPs);
        return allIPs;
    }

    NSLog(@"HTTPDNS resolution failed. Domain name: %@", hostname);
    return nil;
}];

// Set the log level
[EMASLocalHttpProxy setLogLevel:EMASLocalHttpProxyLogLevelDebug];

// Configure the WebView proxy
BOOL proxyConfigured = [EMASLocalHttpProxy installIntoWkWebViewConfiguration:config];
if (proxyConfigured) {
    NSLog(@"WebView proxy configuration successful.");
} else {
    NSLog(@"WebView proxy configuration failed. Using the system network.");
}

WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
Important

Before you deploy to a production environment, read and understand the code implementation logic. Perform thorough testing to ensure full compatibility.

3.3 Implementation details

The complete implementation of EMASLocalProxy is based on the ProxyConfigurations API and the Network.framework for iOS 17.0 and later. It provides a high-performance local proxy service. For details about the technical implementation, see the open-source code:

GitHub source code: https://github.com/aliyun/alicloud-ios-sdk-emascurl/tree/master/EMASLocalProxy

The core technical points are as follows:

  • Use the Network framework to create a local HTTP proxy server.

  • Process HTTP requests through a CONNECT tunnel.

  • Implement transparent data forwarding between the client and the target server.

  • Integrate a custom DNS resolver to support HTTPDNS.

  • Provide a complete fallback and error handling mechanism.

3.4 Fallback and optimization solutions

EMASLocalHttpProxy was designed to handle multiple abnormal scenarios. It has built-in multilayer protection and automatic fallback mechanisms. The goal is to provide high-performance local proxy capabilities while ensuring system high availability (HA) and that the final network requests are reachable. Even when components fail or external dependencies are abnormal, the impact on the user experience is minimized.

The following table describes different abnormal scenarios and their corresponding measures:

Scenario

Trigger

Fallback or protection measure

Final effect

Proxy startup

Port conflict

Automatically retry with a random port

Increases the startup success rate

Startup blocked

Exits on startup timeout

Prevents the application from freezing

Proxy runtime

nw_listener crash

Marks the service as "not running"

Triggers subsequent fallback policies

External access attempt

Listens only on 127.0.0.1

Rejects local area network (LAN) access to ensure security

WebView configuration

Service not running

Uses a non-persistent WKWebsiteDataStore

Falls back to the default system network

System version is earlier than iOS 17

Skips proxy configuration

Maintains consistency with the default system behavior

DNS resolution

Custom resolver throws an exception

Catches the exception and uses the original domain name for local DNS resolution

Prevents connection failures due to resolution errors

Network connection

Connection to the target server failed

Returns a 502 Bad Gateway response

Provides standardized failure feedback

This multilayer design allows HttpdnsLocalHttpProxy to operate reliably in complex and changing network environments. Its complete fallback mechanism ensures that the request path is not interrupted even if some components fail.

4. Global NSURLProtocol interception solution

This solution was the earliest feasible option for integrating HTTPDNS with iOS WebView. It has a very high barrier to entry and is not very effective. However, it has persisted because iOS did not offer other choices in its early years. Its principle is based on NSURLProtocol, which can intercept network requests sent from upper-layer network libraries such as NSURLConnection/NSURLSession on iOS. Requests from WKWebView are also included. After intercepting the requests, the solution uses HTTPDNS for domain name resolution and subsequent processing. The steps are as follows:

  1. You can register a custom NSURLProtocol through the following interface to intercept upper-layer network requests from WKWebView. You can then create a new network request to take over data sending, receiving, redirection, and other processing logic. The results are then fed back to the original request.

    [NSURLProtocol registerClass:[HttpDnsNSURLProtocolImpl class]];
  2. The following is an overview of the custom NSURLProtocol processing procedure:

    • In canInitWithRequest, filter the requests that require HTTPDNS domain name resolution.

    • After the request is intercepted, perform HTTPDNS domain name resolution.

    • After resolution is complete, replace the URL.host field and the HTTP Header Host field, similar to a normal request. Then, take over the data sending, receiving, redirection, and other processing for this request.

    • Use the NSURLProtocol interface to feed the request processing results back to the original WebView request.

  3. For more information about the implementation logic of the custom NSURLProtocol, see HttpDnsNSURLProtocolImpl.m in the provided demo.

Warning

Because Apple has not officially disclosed many protocol details, you must handle details such as cookies and redirection as needed to make this solution feasible in a production environment. Do not use this solution unless you have special requirements.

5. Solution summary and comparison

This document introduces two main technical solutions for integrating HTTPDNS in WKWebView scenarios on iOS: the local proxy solution based on iOS 17 and later, and the global NSURLProtocol interception solution.

Each solution has its specific scenarios, advantages, disadvantages, and implementation complexity. To help you make a quick decision, the following table provides a side-by-side comparison of these two solutions:

Dimension / Solution

Local Proxy (ProxyConfiguration) (iOS 17+)

Global NSURLProtocol Interception

Official Support

A formal, public API introduced by Apple in iOS 17 that is available for long-term use.

Uses the public NSURLProtocol API, but it lacks official documentation about the internal details of WKWebView.

Effective Version

iOS 17 and later. For versions earlier than iOS 17, the proxy is inactive and has no side effects.

iOS 11 and later

Protocol Coverage

HTTP, HTTPS, WebSocket, and HTTP/2 (transparently forwards original traffic).

Limited to protocols that can be handled by NSURLSession and NSURLConnection.

Implementation Complexity

Medium: Requires implementing a local proxy, port management, and bidirectional forwarding.

Medium: Requires handling request rewriting, thread interactions, and cache interactions.

Intrusiveness to Business Code

Low: WKWebView only needs proxy configuration.

Medium: Globally registers NSURLProtocol, which might affect existing NSURLSession logic.

Cookies / Cache / CORS

Transparent at the proxy layer. No extra handling is needed.

Developers need to maintain this themselves, and it is easy to miss edge cases.

Maintenance Cost

Low: Relies on official APIs, with a low risk of version upgrade issues.

Medium: The system API is stable, but it requires attention to internal behavior changes in WKWebView.

Failure Fallback Policy

Supported. It can fall back to the system network if the proxy fails.

Requires self-implementation.

Recommended Scenario

Main recommended solution: For target users on iOS 17 or later who have high requirements for security and compatibility.

For lightweight modification and quick verification, with low requirements for complex request compatibility.

Considering stability, development and maintenance costs, and future trends, we strongly recommend the local proxy solution based on iOS 17 and later.

With the rapid adoption of iOS 17 and later system versions, this solution provides stable and reliable HTTPDNS services to the vast majority of users at a minimal cost. It effectively solves domain hijacking and improves network performance. Its elegant implementation and official support ensure the long-term feasibility of the solution. For system versions earlier than iOS 17, a smooth fallback strategy is used. This means the system's default network requests are used. When users upgrade their systems, they automatically benefit from HTTPDNS.

The other solution has inherent complexity and uncertainty. Adopt it with caution. It is recommended only for teams with special requirements and deep technical expertise, after careful evaluation and thorough testing.