How to send https request through proxy server using URLSession?

The api service I was using was blocked in some regions, so now I need to send https requests through a proxy server. Can someone tell what function/library/something else I need to send a request through a proxy server?

This is my code:

let headers = [
    "x-rapidapi-key": "<my key>",
    "x-rapidapi-host": "weatherapi-com.p.rapidapi.com"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://weatherapi-com.p.rapidapi.com/forecast.json?q=\(latitude)%2C%20\(longitude)&days=\(daylyScrollLength)&lang=ru")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if let data, let weather = try? JSONDecoder().decode(WeatherForecastData.Data.self, from: data){
        weatherData(weather)
    }
})

dataTask.resume()

Straight answer:

To send HTTPS requests through a proxy in Swift, you need to create a custom URLSession with a proxy configured in the URLSessionConfiguration.

Here’s how to modify your code to use a proxy:


Add proxy configuration:

let proxyHost = "YOUR_PROXY_IP"
let proxyPort = 8080 // Replace with your proxy port

let config = URLSessionConfiguration.default
config.connectionProxyDictionary = [
    kCFNetworkProxiesHTTPEnable as String: true,
    kCFNetworkProxiesHTTPProxy as String: proxyHost,
    kCFNetworkProxiesHTTPPort as String: proxyPort,
    kCFNetworkProxiesHTTPSEnable as String: true,
    kCFNetworkProxiesHTTPSProxy as String: proxyHost,
    kCFNetworkProxiesHTTPSPort as String: proxyPort
]

let session = URLSession(configuration: config)

Update your session:

Replace this line:

let session = URLSession.shared

With:

let session = URLSession(configuration: config)

Notes:

  • This method supports HTTP and HTTPS proxies.
  • Authentication? If your proxy requires a username and password, more setup is needed with URLCredential and URLSessionDelegate.