Swift Tunnel Proxy: Alamofire and URLSession

Swift Alamofire and URLSession integrating 16Yun Crawler Proxy.

16Yun Engineering TeamApr 27, 20261 min read

URLSession

URLSession 通过 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

// 代理认证通过 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)
    }
}

两种方案对比

特性URLSessionAlamofire
依赖无(系统库)需 SPM/CocoaPods
代理配置connectionProxyDictionary同 URLSession
代理认证URLCredentialURLCredential
API 风格回调 + delegate链式 .response

Need an enterprise proxy plan?

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