Zum Inhalt springen
GProxy
Registrierung
Гайды 2 Min. Lesezeit 23 Aufrufe

Verwenden von Proxies in Swift

Proxy-Einrichtung in Swift für iOS und macOS: URLSession, Network-Framework, SOCKS5 und Systemkonfiguration.

Verwenden von Proxies in Swift

Verwendung von Proxys in Swift

Proxys in Swift

Swift ist die primäre Sprache für die Entwicklung von iOS- und macOS-Anwendungen. Die Arbeit mit Proxys in Swift erfolgt über URLSession (eine High-Level-API), das Network-Framework (Low-Level) und die Systemeinstellungen.

URLSession mit Proxys

Konfiguration über 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()

SOCKS-Proxy

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

Mit Authentifizierung

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

System-Proxy-Einstellungen

Automatische Verwendung

Standardmäßig verwendet URLSession System-Proxys:

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

Wenn der Benutzer Proxys in den iOS/macOS-Systemeinstellungen konfiguriert hat, verwendet URLSession diese automatisch.

PAC-Datei

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

Umgang mit Proxy-Authentifizierungs-Challenges

Wenn ein Proxy eine Authentifizierung erfordert, ruft URLSession seinen Delegate auf:

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)

Für Low-Level-Netzwerkoperationen in 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 mit Proxys

Alamofire ist eine beliebte Swift HTTP-Bibliothek:

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)
    }
}

iOS-Besonderheiten

VPN und Proxys in iOS

iOS ermöglicht die Proxy-Konfiguration über:
1. Systemeinstellungen (Einstellungen → WLAN → HTTP-Proxy)
2. MDM-Profile
3. NEProxySettings (Network Extension Framework)

Network Extension

Um eine vollwertige Proxy-Anwendung unter iOS zu erstellen, verwenden Sie 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
    }
}

Dies erfordert eine Berechtigung (Entitlement) von Apple und ist für Enterprise-/MDM-Lösungen geeignet.

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) ?? ""
}

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

Fazit

Swift bietet flexible Tools für die Arbeit mit Proxys: URLSession für High-Level-Aufgaben, das Network-Framework für Low-Level-Kontrolle und Network Extension für die Erstellung von Proxy-Anwendungen. Für die meisten Aufgaben ist URLSession mit connectionProxyDictionary die optimale Wahl.

Aktualisiert: 06.03.2026
Zurück zur Kategorie

Testen Sie unsere Proxys

20.000+ Proxys in über 100 Ländern weltweit

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