Ir al contenido
GProxy
Registro
Гайды 3 min de lectura 22 vistas

Usando Proxies en Swift

Configuración de proxy en Swift para iOS y macOS: URLSession, Network framework, SOCKS5 y configuración del sistema.

Usando Proxies en Swift

Traducir este texto al español. Mantener TODO el formato Markdown, enlaces, bloques de código, tablas intactos. No añadir explicaciones.

Usando Proxies en Swift

Proxies en Swift

Swift es el lenguaje principal para desarrollar aplicaciones iOS y macOS. Trabajar con proxies en Swift se realiza a través de URLSession (una API de alto nivel), el framework Network (de bajo nivel) y la configuración del sistema.

URLSession con Proxies

Configuración vía URLSessionConfiguration

import Foundation

let config = URLSessionConfiguration.default

// HTTP proxy configuration
config.connectionProxyDictionary = [
    kCFNetworkProxiesHTTPEnable: true,
    kCFNetworkProxiesHTTPProxy: "proxy_ip",
    kCFNetworkProxiesHTTPPort: 8080,
    kCFNetworkProxiesHTTPSEnable: true,
    kCFNetworkProxiesHTTPSProxy: "proxy_ip",
    kCFNetworkProxiesHTTPSPort: 8080
]

let session = URLSession(configuration: config)

let url = URL(string: "https://httpbin.org/ip")!
let task = session.dataTask(with: url) { data, response, error in
    if let data = data, let body = String(data: data, encoding: .utf8) {
        print(body)
    }
}
task.resume()

Proxy SOCKS

config.connectionProxyDictionary = [
    kCFStreamPropertySOCKSProxyHost: "proxy_ip",
    kCFStreamPropertySOCKSProxyPort: 1080,
    kCFStreamPropertySOCKSVersion: kCFStreamSocketSOCKSVersion5
]

Con Autenticación

config.connectionProxyDictionary = [
    kCFNetworkProxiesHTTPEnable: true,
    kCFNetworkProxiesHTTPProxy: "proxy_ip",
    kCFNetworkProxiesHTTPPort: 8080,
    kCFProxyUsernameKey: "username",
    kCFProxyPasswordKey: "password"
]

Configuración de Proxy del Sistema

Uso Automático

Por defecto, URLSession utiliza los proxies del sistema:

let config = URLSessionConfiguration.default
// Uses system proxies by default
let session = URLSession(configuration: config)

Si el usuario ha configurado proxies en la configuración del sistema de iOS/macOS, URLSession los utilizará automáticamente.

Archivo PAC

config.connectionProxyDictionary = [
    kCFNetworkProxiesProxyAutoConfigEnable: true,
    kCFNetworkProxiesProxyAutoConfigURLString: "http://example.com/proxy.pac"
]

Manejo del Desafío de Autenticación de Proxy

Cuando un proxy requiere autenticación, URLSession invoca a su delegado:

class ProxyDelegate: NSObject, URLSessionDelegate {
    func urlSession(
        _ session: URLSession,
        didReceive challenge: URLAuthenticationChallenge,
        completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
    ) {
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodHTTPBasic
            && challenge.protectionSpace.isProxy {
            let credential = URLCredential(
                user: "username",
                password: "password",
                persistence: .forSession
            )
            completionHandler(.useCredential, credential)
        } else {
            completionHandler(.performDefaultHandling, nil)
        }
    }
}

let delegate = ProxyDelegate()
let session = URLSession(configuration: config, delegate: delegate, delegateQueue: nil)

Network Framework (NWConnection)

Para operaciones de red de bajo nivel en iOS 12+ / macOS 10.14+:

import Network

let proxyConfig = NWProtocolTLS.Options()
let params = NWParameters.tls

// Proxy configuration via NWEndpoint
let proxyEndpoint = NWEndpoint.hostPort(
    host: NWEndpoint.Host("proxy_ip"),
    port: NWEndpoint.Port(rawValue: 8080)!
)

// Creating a connection
let connection = NWConnection(
    host: "httpbin.org",
    port: 443,
    using: params
)

connection.stateUpdateHandler = { state in
    switch state {
    case .ready:
        print("Connected")
    case .failed(let error):
        print("Failed: \(error)")
    default:
        break
    }
}

connection.start(queue: .global())

Alamofire con Proxies

Alamofire es una popular librería HTTP de Swift:

import Alamofire

let config = URLSessionConfiguration.default
config.connectionProxyDictionary = [
    kCFNetworkProxiesHTTPEnable: true,
    kCFNetworkProxiesHTTPProxy: "proxy_ip",
    kCFNetworkProxiesHTTPPort: 8080
]

let session = Session(configuration: config)

session.request("https://httpbin.org/ip").response { response in
    if let data = response.data, let body = String(data: data, encoding: .utf8) {
        print(body)
    }
}

Especificidades de iOS

VPN y Proxies en iOS

iOS permite la configuración de proxy a través de:
1. Configuración del Sistema (Ajustes → Wi-Fi → Proxy HTTP)
2. Perfiles MDM
3. NEProxySettings (framework Network Extension)

Network Extension

Para crear una aplicación de proxy completa en iOS, usa NETransparentProxyProvider:

import NetworkExtension

class ProxyProvider: NETransparentProxyProvider {
    override func startProxy(options: [String: Any]?, completionHandler: @escaping (Error?) -> Void) {
        // Proxy configuration
        completionHandler(nil)
    }

    override func handleNewFlow(_ flow: NEAppProxyFlow) -> Bool {
        // Handling a new connection
        return true
    }
}

Esto requiere una autorización de Apple y es adecuado para soluciones empresariales/MDM.

async/await (Swift 5.5+)

func fetchViaProxy() async throws -> String {
    let config = URLSessionConfiguration.default
    config.connectionProxyDictionary = [
        kCFNetworkProxiesHTTPEnable: true,
        kCFNetworkProxiesHTTPProxy: "proxy_ip",
        kCFNetworkProxiesHTTPPort: 8080
    ]

    let session = URLSession(configuration: config)
    let url = URL(string: "https://httpbin.org/ip")!
    let (data, _) = try await session.data(from: url)
    return String(data: data, encoding: .utf8) ?? ""
}

// Usage
Task {
    let ip = try await fetchViaProxy()
    print(ip)
}

Conclusión

Swift proporciona herramientas flexibles para trabajar con proxies: URLSession para tareas de alto nivel, el framework Network para control de bajo nivel y Network Extension para crear aplicaciones de proxy. Para la mayoría de las tareas, URLSession con connectionProxyDictionary es la opción óptima.

Actualizado: 06.03.2026
Volver a la categoría

Pruebe nuestros proxies

20,000+ proxies en 100+ países del mundo

support_agent
GProxy Support
Usually replies within minutes
Hi there!
Send us a message and we'll reply as soon as possible.