All Products
Search
Document Center

HTTPDNS:Integrate the SDK for iOS

Last Updated:Dec 16, 2025

Introduction

This topic describes how to integrate the HTTPDNS SDK for iOS.

  • You can use CocoaPods to manage dependencies in your project.

  • The latest version of the SDK supports iOS Deployment Target 10.0 and later.

  • The SDK is packaged as a static library.

  • It supports the x86_64 and arm64 architectures for emulators, and the arm64 architecture for physical devices.

Step 1: Add the SDK to your application

1. Specify the Master and Alibaba Cloud repositories

The HTTPDNS SDK for iOS and other EMAS SDKs for iOS are published to the official GitHub repository that is maintained by Alibaba Cloud EMAS. You must include the repository address in your Podfile.

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

2. Add dependencies

Add the following dependency to the target that uses the HTTPDNS iOS SDK.

use_framework!

pod 'AlicloudHTTPDNS', 'x.x.x'
Important

Update the example to use the latest version number from the release notes.

3. Install dependencies

In your terminal, navigate to the folder that contains the Podfile. Run the following command to install the dependencies.

pod install --repo-update
Important

After the installation is complete, reopen your project using the .xcworkspace file.

Step 2: Use the SDK

1. Import the header file

Import the header file into the code files that use HTTPDNS.

#import <AlicloudHttpDNS/AlicloudHttpDNS.h>
import AlicloudHttpDNS

2. Create and configure an HTTPDNS instance

Create and configure a global HTTPDNS instance in the -[AppDelegate application:didFinishLaunchingWithOptions:] method.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    // Create a global instance using the AccountId assigned in the Alibaba Cloud HTTPDNS console.
    // The instance needs to be initialized only once globally. Obtain the authentication key from the console and configure the secretKey during initialization.
    HttpDnsService *httpdns = [[HttpDnsService alloc] initWithAccountID:<Your AccountId> secretKey:@"<Your SecretKey>"];

    // Enable logging for debugging and troubleshooting.
    [httpdns setLogEnabled:NO];

    // Specify whether to use HTTPS for domain name resolution requests.
    [httpdns setHTTPSRequestEnabled:YES];
    
    // Set the startup node. Select a startup node based on your scenario.
    [httpdns setRegion:ALICLOUD_HTTPDNS_SINGAPORE_REGION_KEY];
    
    // Enable persistent cache so that the app can reuse the IP addresses cached locally from the last active session. This speeds up the retrieval of domain name resolution results after the app starts.
    [httpdns setPersistentCacheIPEnabled:YES];

    // Allow the use of expired IP addresses. You can enable this feature to improve resolution efficiency if the IP configuration of the domain name is stable.
    [httpdns setReuseExpiredIPEnabled:YES];

    // Set the timeout period for underlying HTTPDNS network requests. Unit: seconds.
    [httpdns setNetworkingTimeoutInterval:2];

    return YES;
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    // Create a global instance using the AccountId assigned in the Alibaba Cloud HTTPDNS console.
    // The instance needs to be initialized only once globally. Obtain the authentication key from the console and configure the secretKey during initialization.
    let httpdns = HttpDnsService(accountID: <Your AccountId>, secretKey: "<Your SecretKey>")

    // Enable logging for debugging and troubleshooting.
    httpdns.setLogEnabled(false)

    // Specify whether to use HTTPS for domain name resolution requests.
    httpdns.setHTTPSRequestEnabled(true)
    
    // Set the startup service node. Select a startup node based on your scenario.
    httpdns.setRegion(ALICLOUD_HTTPDNS_SINGAPORE_REGION_KEY)

    // Enable persistent cache so that the app can reuse the IP addresses cached locally from the last active session. This speeds up the retrieval of domain name resolution results after the app starts.
    httpdns.setPersistentCacheIPEnabled(true)

    // Allow the use of expired IP addresses. You can enable this feature to improve resolution efficiency if the IP configuration of the domain name is stable.
    httpdns.setReuseExpiredIPEnabled(true)

    // Specify whether to support IPv6 address resolution. Only when this switch is turned on can the resolution interface resolve and return the IPv6 address of the domain name.
    httpdns.setIPv6Enabled(true)

    return true
}
Important
  • Enable setPersistentCacheIPEnabled:YES and setReuseExpiredIPEnabled:YES to implement optimistic DNS caching. This feature persistently stores resolution results and allows the use of expired IP addresses. As a result, most DNS resolutions can be completed locally, which improves first-screen loading and request performance. We recommend that you enable this feature for business domain names whose resolved IP addresses do not change frequently. For more information, see the descriptions of the Enable persistent cache and Allow the use of expired IP addresses interfaces.

  • If you set the setHTTPSRequestEnabled parameter to `true`, your costs will increase. For more information, see the Product Billing document.

  • If you have high security requirements for domain name information or SDNS parameters, you can enable the encryption feature by setting `aesSecretKey` through the initialization interface. After you enable content encryption, your costs will increase. For more information, see the Product Billing document.

  • Use the pre-resolution interface to enable domain name pre-resolution. This significantly increases the hit rate of the optimistic DNS cache, which allows most resolution requests to be returned directly from the local cache and reduces the latency that is caused by real-time resolution. However, pre-resolution increases the number of resolution requests. We recommend that you enable this feature only for core business domain names or frequently accessed domain names to achieve the best balance between performance and cost.

  • By default, `setRegion` uses service nodes in the Chinese mainland. If your application needs to use HTTPDNS outside China, you can set the startup service node for this SDK to improve resolution efficiency. For more information, see Set the region node.

3. Obtain the service instance

The HTTPDNS SDK for iOS provides domain name resolution services through a global service instance. You can retrieve the instance as follows.

HttpDnsService *httpdns = [HttpDnsService sharedInstance];
let httpdns = HttpDnsService.sharedInstance()

4. Resolve a domain name

HTTPDNS provides multiple domain name resolution methods, such as pre-resolution, synchronous resolution, asynchronous resolution, and synchronous non-blocking resolution. The following example uses the synchronous non-blocking resolution interface.

HttpDnsService *httpdns = [HttpDnsService sharedInstance];
HttpdnsResult *result = [httpdns resolveHostSyncNonBlocking:@"www.aliyun.com" byIpType:HttpdnsQueryIPTypeAuto];
if (result) {
    // Use the domain name resolution result.
} else {
    // The synchronous non-blocking interface immediately returns null if no valid resolution result is found in the cache to ensure the fastest resolution speed. A new resolution request is initiated in the background.
    // Therefore, you must prepare to fall back to LocalDNS resolution or pass the full domain name directly to the network library.
    // You can use a synchronous interface or a callback-based interface to ensure that you obtain the HTTPDNS resolution result.
}
let httpdns = HttpDnsService.sharedInstance()
if let result = httpdns.resolveHostSyncNonBlocking("www.aliyun.com", by: HttpdnsQueryIPType.auto) {
    // Use the domain name resolution result.
} else {
    // The synchronous non-blocking interface immediately returns null if no valid resolution result is found in the cache to ensure the fastest resolution speed. A new resolution request is initiated in the background.
    // Therefore, you must prepare to fall back to LocalDNS resolution or pass the full domain name directly to the network library.
    // You can use a synchronous interface or a callback-based interface to ensure that you obtain the HTTPDNS resolution result.
}

Select a domain name resolution interface based on your business scenario.

Important
  • If the returned result is always nil, check whether you have added the domain name in the Alibaba Cloud HTTPDNS console.

  • To prevent business processes from being affected when the returned result is nil because of network exceptions, fall back to LocalDNS resolution.

5. Use the domain name resolution result

The domain name resolution result may vary based on the situation.

  • An empty result. This can occur when you use the synchronous non-blocking interface or when a network exception occurs.

  • Only an IPv4 address. This occurs when the on-premises network is an IPv4 single-stack environment and the request type specifies IPv4, or when only an IPv4 address is configured for the domain name.

  • Only an IPv6 address. This occurs when IPv6 is enabled and the resolution of an IPv6 address is specified. This scenario is unlikely because of the current adoption rate of IPv6.

  • Both IPv4 and IPv6 addresses. This occurs when IPv6 is enabled and dual-stack address resolution is specified, or when automatic network type detection is specified in a dual-stack environment, and both IPv4 and IPv6 addresses are configured for the domain name.

In this example, IPv6 resolution is enabled, and the requested IP type is set to Both. If both IPv4 and IPv6 addresses are configured for the domain name, the resolution result includes both addresses. Therefore, to prioritize the IPv4 address, you can process the resolution result as shown in the following code.

HttpDnsService *httpdns = [HttpDnsService sharedInstance];
HttpdnsResult *result = [httpdns resolveHostSyncNonBlocking:@"www.aliyun.com" byIpType:HttpdnsQueryIPTypeAuto];
if (!result) {
    // No valid IP address. Fall back to the default logic.
}

if (result.hasIpv4Address) {
    NSString *ip = result.firstIpv4Address;
    // Use the IP address.

    NSArray<NSString *> *ips = result.ips;
    // Use the IP address list.
} else if (result.hasIpv6Address) {
    NSString *ip = result.firstIpv6Address;
    // Use the IP address.

    NSArray<NSString *> *ips = result.ipv6s;
    // Use the IP address list.
} else {
    // No valid IP address. Fall back to the default logic.
}
let httpdns = HttpDnsService.sharedInstance()
if let result = httpdns.resolveHostSyncNonBlocking("www.aliyun.com", by: HttpdnsQueryIPType.auto) {
    if (result.hasIpv4Address()) {
        let ip = result.firstIpv4Address()
        // Use the IP address.

        let ipList = result.ips
        // Use the IP address list.
    } else if (result.hasIpv6Address()) {
        let ip = result.firstIpv6Address()
        // Use the IP address.

        let ipList = result.ipv6s
        // Use the IP address list.
    } else {
        // No valid IP address. Fall back to the default logic.
    }
} else {
    // No valid IP address. Fall back to the default logic.
}

Sample code

For a sample project that shows how to integrate the HTTPDNS SDK for iOS, see HTTPDNS iOS Demo.

Notes

  1. Write fallback code

    Fallback code handles cases where HTTPDNS fails to retrieve the expected result. You can typically fall back to using LocalDNS for resolution. This means passing the original domain name to the network library and letting the library resolve the domain name using the local DNS.

  2. Record the IP address and sessionId retrieved from HTTPDNS

    We provide a solution for troubleshooting resolution issues. You can record the IP address and sessionId that are retrieved from HTTPDNS in your logs. For more information, see How to use the session tracing solution to troubleshoot resolution exceptions.

  3. Set the HOST field in the HTTP request header

    In the standard HTTP protocol, the server parses the value of the `HOST` field in the HTTP request header as the requested domain name. After you use HTTPDNS, you may need to replace the host in the request URL with the IP address that is retrieved from HTTPDNS. A standard network library then assigns this IP address to the `HOST` field of the HTTP request header. This can cause a parsing exception on the server because the server expects the domain name, not the IP address.

    To resolve this issue, you must set the value of the `HOST` field in the HTTP request. The following code provides a simple example:

    - (void)sampleRequestUsingHttpdns {
        HttpDnsService *httpdns = [HttpDnsService sharedInstance];
    
        NSString *originalUrlStr = @"http://www.aliyun.com/";
        NSURL* url = [NSURL URLWithString:originalUrlStr];
    
        // Obtain the IP address using the synchronous interface.
        HttpdnsResult* result = [httpdns resolveHostSyncNonBlocking:url.host byIpType:HttpdnsQueryIPTypeAuto];
        NSLog(@"resolve result: %@", result);
        NSString *validIp = nil;
        if (result) {
            if (result.hasIpv4Address) {
                validIp = result.firstIpv4Address;
            }
        }
    
        NSMutableURLRequest *request;
    
        if (validIp) {
            // The IP address is obtained from HTTPDNS. Replace the URL and set the Host header.
            NSRange hostFirstRange = [originalUrlStr rangeOfString:url.host];
            NSString* newUrl = [originalUrlStr stringByReplacingCharactersInRange:hostFirstRange withString:validIp];
            request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:newUrl]];
            // Set the HOST field of the request.
            [request setValue:url.host forHTTPHeaderField:@"host"];
        } else {
            // This shows how to handle the fallback.
            // The IP address cannot be obtained from HTTPDNS. Use the original URL to make the network request.
            request = [[NSMutableURLRequest alloc] initWithURL:url];
        }
    
        // Send the request.
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error) {
                NSLog(@"error: %@", error);
            } else {
                NSLog(@"response: %@", response);
            }
        }];
        [task resume];
    }
    func sampleRequestUsingHttpdns() {
        let httpdns = HttpDnsService.sharedInstance()
        let originalUrlStr = "http://www.aliyun.com/"
        let url = URL(string: originalUrlStr)!
    
        // Obtain the IP address using the synchronous interface.
        let result = httpdns.resolveHostSyncNonBlocking(url.host!, by: HttpdnsQueryIPType.auto)
        print("resolve result: \(result?.description ?? "")")
    
        var validIp: String?
        if let result = result {
            if result.hasIpv4Address() {
                validIp = result.firstIpv4Address()
            }
        }
    
        var request: URLRequest
    
        if let validIp = validIp {
            // The IP address is obtained from HTTPDNS. Replace the URL and set the Host header.
            let hostFirstRange = originalUrlStr.firstRange(of: url.host!)!
            let newUrl = originalUrlStr.replacingCharacters(in: hostFirstRange, with: validIp)
            request = URLRequest(url: URL(string: newUrl)!)
            // Set the HOST field of the request.
            request.setValue(url.host!, forHTTPHeaderField: "host")
        } else {
            // This shows how to handle the fallback.
            // The IP address cannot be obtained from HTTPDNS. Use the original URL to make the network request.
            request = URLRequest(url: url)
        }
    
        // Send the request.
        let session = URLSession.shared
        let task = session.dataTask(with: request) { (data, response, error) in
            if let error = error {
                print("error: \(error)")
            } else {
                print("response: \(response?.description ?? "")")
            }
        }
        task.resume()
    }
    Important

    In this simple example, also note the following details:

    • This example shows only a successful resolution and does not consider the fallback logic.

    • For simplicity, this example requests an HTTP address. Therefore, you must configure NSAllowsArbitraryLoads in Info.plist to allow access.

    • If the request address is an HTTPS address, see the guidance for HTTPS scenarios later in this document.

  4. Cookie field

    Some network libraries support automatic cookie storage and management. When you use HTTPDNS to make a request to a URL that contains an IP address, some network libraries may store the IP address from the URL as the domain name for the cookie, instead of the value of the `HOST` field from the HTTP request header. This can cause issues with cookie management and usage. Therefore, you must disable the automatic cookie management feature. This feature is disabled by default.

  5. HTTPS, WebView, and SNI scenarios

    For HTTPS scenarios, see Use HTTPDNS in native scenarios on iOS.

  6. Usage with a proxy

    When an intermediate HTTP proxy exists, the request line in the client-initiated request uses an absolute path URL. If you enable HTTPDNS and use a URL that contains an IP address for access, the intermediate proxy identifies the IP address and passes it to the destination server as the actual `HOST` information. The destination server cannot process HTTP requests that lack the real `HOST` information. Mobile Gateway provides the X-Online-Host proprietary protocol field to resolve this issue. For example:

    Destination URL: http://www.aliyun.com/product/oss/
    IP address of www.aliyun.com resolved by HTTPDNS: X.X.X.X
    Proxy: 10.0.0.172:80
    
    Your HTTP request header:
    
    GET http://X.X.X.X/product/oss/ HTTP/1.1     # The request line of an HTTP request initiated through a proxy is an absolute path.
    Host: www.aliyun.com   # This header is ignored by the proxy gateway. The proxy gateway uses the host field in the absolute path of the request line as the host of the origin server, which is X.X.X.X.
    X-Online-Host: www.aliyun.com    # This header is a private header added by Mobile Gateway to transmit the real Host. The origin server needs to be configured to recognize this private header to obtain the real Host information.

    Set the X-Online-Host request header field using the following method. Then, configure the server to parse this private header field.

    [request setValue:url.host forHTTPHeaderField:@"X-Online-Host"];
    Note

    In most scenarios, you can check whether a network proxy is enabled on the current device. If a proxy is enabled, do not use HTTPDNS for domain name resolution.