Swift Tunnel Proxy: Alamofire and URLSession

Swift Alamofire and URLSession integrating 16Yun Crawler Proxy.

16Yun Engineering TeamApr 27, 20261 min read

URLSession

URLSession configures proxies via URLProxy:

import Foundation
 
let host = ProcessInfo.processInfo.environment["PROXY_HOST"] ?? "t.16yun.cn"
let port = ProcessInfo.processInfo.environment["PROXY_PORT"] ?? "31111"
 
let proxyDict: [AnyHashable: Any] = [
    "HTTPEnable": 1,
    "HTTPProxy": host,
    "HTTPPort": Int(port) ?? 31111,
    "HTTPSEnable": 1,
    "HTTPSProxy": host,
    "HTTPSPort": Int(port) ?? 31111,
]
 
let config = URLSessionConfiguration.default
config.connectionProxyDictionary = proxyDict
 
// Proxy authentication via URLCredential
let session = URLSession(configuration: config)
let task = session.dataTask(with: URL(string: "https://httpbin.org/ip")!) { data, _, _ in
    if let data = data, let body = String(data: data, encoding: .utf8) {
        print(body)
    }
}
task.resume()
sleep(2)

Alamofire

import Alamofire
 
let host = ProcessInfo.processInfo.environment["PROXY_HOST"] ?? "t.16yun.cn"
let port = ProcessInfo.processInfo.environment["PROXY_PORT"] ?? "31111"
 
let proxyDict: [AnyHashable: Any] = [
    kCFNetworkProxiesHTTPEnable: true,
    kCFNetworkProxiesHTTPProxy: host,
    kCFNetworkProxiesHTTPPort: Int(port) ?? 31111,
    kCFNetworkProxiesHTTPSEnable: true,
    kCFNetworkProxiesHTTPSProxy: host,
    kCFNetworkProxiesHTTPSPort: Int(port) ?? 31111,
]
 
let config = URLSessionConfiguration.default
config.connectionProxyDictionary = proxyDict
 
let session = Session(configuration: config)
session.request("https://httpbin.org/ip").responseString { resp in
    if let body = resp.value {
        print(body)
    }
}

Comparison of Two Approaches

FeatureURLSessionAlamofire
DependencyNone (system library)Requires SPM/CocoaPods
Proxy ConfigconnectionProxyDictionarySame as URLSession
Proxy AuthURLCredentialURLCredential
API StyleCallback + delegateChained .response

Need an enterprise proxy plan?

We can tailor architecture to your target domains, concurrency, and reliability goals.