Zum Inhalt springen
Guides 2 Min. Lesezeit 873 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

Lesen Sie auch

Guides 2 Min.

Proxy für Nike SNKRS: Limitierte Drops ergattern & mehrere Teilnahmen sichern

Nutze Residential- oder Mobile-Proxies für Nike SNKRS, um mit mehreren Accounts an Draws teilzunehmen, IP-Limits zu umgehen und limitierte Drops ohne Bans zu coppen. Welcher Typ zu wählen ist und wie man das Setup einrichtet.

Guides 2 Min.

So richten Sie einen Proxy auf dem iPhone ein (WLAN & SOCKS5)

Richten Sie einen Proxy auf dem iPhone über die nativen Wi-Fi-Einstellungen (HTTP/HTTPS) oder eine Proxy-App wie Shadowrocket für SOCKS5 und Mobilfunkabdeckung ein. Schritt-für-Schritt-iOS-Setup und die zu beachtenden Einschränkungen.

Guides 3 Min.

Proxy für Tinder: Mehrere Accounts & Sperren vermeiden

Nutze Mobile- oder Residential-Proxies für Tinder, um mehrere Profile zu betreiben und IP-Shadowbans zu vermeiden. Warum Mobile gewinnt, wie man es einrichtet und warum ein Proxy allein nicht deinen Standort ändert.

Guides 2 Min.

Proxy für StockX: Preise überwachen & Accounts verwalten

Nutzen Sie Residential-, ISP- oder Mobile-Proxys für StockX, um Preise zu überwachen, mehrere Accounts zu verwalten und Drops ohne Bans zu coppen. Hier erfahren Sie, welchen Typ Sie wählen sollten und wie Sie GProxy einrichten.

Guides 3 Min.

Proxy für OpenAI API: Zugriff, Rate Limits & Setup

Leite die OpenAI API über einen Residential- oder ISP-Proxy (GProxy +) weiter, um auf unterstützte Regionen zuzugreifen, 429-Rate-Limits zu umgehen und Accounts zu isolieren. Welcher Proxy zu verwenden ist, plus Python-Setup-Beispiele.

Guides 1 Min.

Einrichten eines Proxys in Cypress für E2E-Tests

Einrichten eines Proxys in Cypress: HTTP_PROXY-Variablen, cy-proxy-middleware und das Testen standortabhängiger Inhalte.

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.