How to Use a Proxy with Swift URLSession on iOS and macOS

Published:

9 minute read

Acar Diveroli
Written by: Acar Diveroli
A blue proxyConfigurations row on the settings card in the URLSession block's slot; a dashed URLRequest card in front

In URLSession, a proxy is a setting on the URLSessionConfiguration object that creates the session. From iOS 17 and macOS 14, the way to set it is the proxyConfigurations array. This array defines HTTP CONNECT and SOCKS5 proxies together with a username and password. Older versions use connectionProxyDictionary, but that dictionary has no password field. This post covers both APIs, 407 authentication, how an in-app proxy differs from the device proxy, and how to test it.

Where the proxy setting lives

URLSession reads the proxy from the session's configuration, not from the request. URLRequest has no proxy field. The proxy is written to a URLSessionConfiguration object, and the session is created with that object.

Order matters. A session takes a copy of the configuration when it is created. If you change the configuration after creating the session, that session keeps the old settings. If you need a different proxy, create a new session.

Both settings are empty by default. With an empty setting, requests follow the system proxy settings. Once the setting is filled, that session ignores the system settings.

PropertyproxyConfigurationsconnectionProxyDictionary
VersioniOS 17, macOS 14 and lateriOS 7, macOS 10.9 and later
TypeHTTP CONNECT, SOCKS5, relayHTTP and HTTPS proxy
PasswordIn the configuration via applyCredentialNot in the configuration, asked on 407
Proxy unreachableError by defaultRequest may go direct

Apple's documentation recommends the proxyConfigurations array. In an app that also supports older versions, separate the two with #available.

iOS 17 and later: ProxyConfiguration

ProxyConfiguration is the Network framework's proxy definition, and URLSession accepts it directly. For an HTTP proxy, use init(httpCONNECTProxy:tlsOptions:). The connection to each target is built through a CONNECT tunnel.

swift
import Foundation
import Network

let endpoint = NWEndpoint.hostPort(host: "pr.proxynet.io", port: 8000)

// tlsOptions: nil -> plain HTTP to the proxy
var proxy = ProxyConfiguration(httpCONNECTProxy: endpoint, tlsOptions: nil)
proxy.applyCredential(username: "user", password: "pass")

let config = URLSessionConfiguration.ephemeral
config.proxyConfigurations = [proxy]

let session = URLSession(configuration: config)

tlsOptions controls the connection to the proxy itself. For a proxy port that speaks plain HTTP, pass nil. If the proxy endpoint expects TLS, pass NWProtocolTLS.Options(). This value stays the same when the target site is HTTPS, because the target's TLS connection is built inside the tunnel.

The password never goes into a URL. So a password containing @ or # needs no percent-encoding. applyCredential takes the original password.

allowFailover defaults to false. If the proxy is unreachable, the request fails and does not leave from your own IP. Leave failover off. A proxy that silently drops out is harder to notice than an error message.

SOCKS5 connection

For SOCKS5, use init(socksv5Proxy:). The credentials are again added with applyCredential and sent in the SOCKS5 username and password step.

swift
var socks = ProxyConfiguration(
    socksv5Proxy: .hostPort(host: "pr.proxynet.io", port: 8000)
)
socks.applyCredential(username: "user", password: "pass")

let config = URLSessionConfiguration.ephemeral
config.proxyConfigurations = [socks]

Older versions are a different story. On iOS there is no documented Swift way to define SOCKS5 through connectionProxyDictionary. The SOCKS constants are visible in Swift only on macOS. If an app that supports iOS 16 and earlier needs SOCKS5, consider raising the minimum version. Proxynet SOCKS5 Proxy uses the same credentials as the HTTP proxy.

Older versions: connectionProxyDictionary

connectionProxyDictionary is a dictionary filled with CFNetwork keys. The HTTP keys are available from Swift on iOS and macOS. The HTTPS keys are defined in Swift only for macOS.

swift
let config = URLSessionConfiguration.ephemeral
config.connectionProxyDictionary = [
    kCFNetworkProxiesHTTPEnable as String: 1,
    kCFNetworkProxiesHTTPProxy as String: "pr.proxynet.io",
    kCFNetworkProxiesHTTPPort as String: 8000,
    // No HTTPS constants on iOS; their values are these same strings
    "HTTPSEnable": 1,
    "HTTPSProxy": "pr.proxynet.io",
    "HTTPSPort": 8000,
]

The HTTPS lines are a safeguard. On Apple's developer forums, an answer said iOS applies the HTTP setting to HTTPS as well. In the same thread, other developers saw HTTPS requests bypass the proxy. Since the constants' string values are the same, writing both groups of lines is the safe path.

This path has two limits. The first is the password: the dictionary has no documented username or password key. The second is failure behavior. According to Apple's forum answer, the proxy system is designed to make the request work. If the proxy connection fails, the request may go direct.

Authentication and 407

When the proxy wants credentials, it returns 407, and URLSession turns that into an authentication challenge. The challenge's protectionSpace.isProxy() returns true. With the older API, this is where you supply the password as a URLCredential.

Adding the Proxy-Authorization header by hand does not work. Apple lists this header among the reserved headers. The system may ignore the value, replace it with its own, or not send it at all. The behavior can also change between versions.

swift
final class ProxyAuth: NSObject, URLSessionTaskDelegate {
    func urlSession(
        _ session: URLSession,
        task: URLSessionTask,
        didReceive challenge: URLAuthenticationChallenge,
        completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
    ) {
        guard challenge.protectionSpace.isProxy() else {
            completionHandler(.performDefaultHandling, nil)
            return
        }
        // If the password was rejected once, don't loop
        if challenge.previousFailureCount > 0 {
            completionHandler(.cancelAuthenticationChallenge, nil)
            return
        }
        let credential = URLCredential(user: "user", password: "pass", persistence: .forSession)
        completionHandler(.useCredential, credential)
    }
}

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

Pass the delegate when the session is created. It cannot be assigned later. The previousFailureCount check prevents endless retries with a wrong password.

There is also a known issue. Posts on Apple's forums report that with a custom proxy dictionary, a 407 opens the system's own password prompt instead of calling the delegate. If users see this prompt, switch to applyCredential on iOS 17 and later. The general causes of 407 are in the HTTP 407 error post.

Device proxy and in-app proxy

A device proxy affects every app. A URLSession setting affects only that session. The Wi-Fi proxy in Settings applies to the default traffic of apps on that network. A proxy you set in code applies only to requests that go through your session.

TopicDevice proxyURLSession setting
ScopeAll apps on the networkThat session only
Who controls itThe userApp code
When the network changesSeparate setting per networkSetting stays the same
PasswordUser enters it in SettingsSupplied in code

A session with an empty setting follows the device proxy. Once you fill the setting, the device setting is ignored for that session. Routing the whole device's traffic through a proxy is not a coding task. For that, see the iPhone proxy app post.

Testing

Testing starts by checking the credentials before the code. Try the same address and password from a computer with curl first:

bash
curl -x http://pr.proxynet.io:8000 \
  --proxy-user user:pass \
  https://api.ipify.org

If curl returns an IP, the proxy side is ready. Then send a request to the same address from the app and compare the returned IP with your own:

swift
let url = URL(string: "https://api.ipify.org")!
let (data, response) = try await session.data(from: url)
let status = (response as? HTTPURLResponse)?.statusCode ?? 0
print(status, String(decoding: data, as: UTF8.self))

If the two IPs match, the request did not go through the proxy. Check each setting separately. On the older dictionary path, a request can go direct without any error.

The simulator uses the Mac's network connection. A system proxy enabled on the Mac changes the result for sessions with an empty setting. Do the final check on a real device, on Wi-Fi and mobile data separately. If you need to see your app from mobile carrier IPs, Mobile Proxy works with the same code.

Troubleshooting

Most symptoms come from setting the configuration in the wrong place or at the wrong time.

SymptomLikely causeFix
IP does not change, no errorSetting applied after the session was createdCreate the session with the new configuration
HTTPS requests bypass the proxyNo HTTPS keys in the dictionaryAdd the "HTTPSProxy" lines
System password prompt appearsDictionary path plus 407Use applyCredential
Repeated 407Wrong passwordVerify with curl first
proxyConfigurations does not compileDeployment target below iOS 17Separate with #available
kCFNetworkProxiesHTTPSProxy not foundConstant missing in Swift on iOSWrite the string key

If you get connection errors with ProxyConfiguration, check the host and port first. With allowFailover off, the request does not go direct. It fails, and that is the expected behavior.

The bottom line

On iOS 17, macOS 14 and later, use ProxyConfiguration with applyCredential, and support older versions with the dictionary behind #available. Above all, compare the IP returned in testing with your own: on the older path the proxy can drop out without an error. If your credentials are ready, you can make the first attempt with Residential Proxy.

Sources

Frequently asked questions

Can I change the URLSession proxy setting after the session is created?

No. A session takes a copy of the URLSessionConfiguration object when it is created. Changing proxyConfigurations or connectionProxyDictionary later does not affect that session. For a different proxy or different credentials, create a new session. If you close the old session with finishTasksAndInvalidate(), pending requests complete and new ones go through the new session.

Does URLSession support SOCKS5 proxies?

Yes, from iOS 17 and macOS 14. Create a definition with ProxyConfiguration(socksv5Proxy:), add the credentials with applyCredential and pass it to the proxyConfigurations array. On older iOS versions the SOCKS keys are not visible in Swift, so there is no documented path. These constants are defined in Swift only for macOS.

Can I add the Proxy-Authorization header manually?

No. Apple lists Proxy-Authorization among the reserved headers managed by the URL Loading System. If you set it on a URLRequest, the system may ignore, replace or drop the value. Pass the password with applyCredential on iOS 17 and later, and with a URLCredential in answer to the 407 challenge on older versions.

Does WKWebView use the URLSession proxy setting?

No. WKWebView uses its own networking layer and does not see your URLSession configuration. iOS 17 and macOS 14 brought the WKWebsiteDataStore.proxyConfigurations property to WebKit. It takes the same ProxyConfiguration type. Set it on the data store before the web view loads a page, and verify it with a separate test page.

Does the same setting work with Alamofire?

Yes. Alamofire is built on URLSession and takes a URLSessionConfiguration through Session(configuration:). Write the proxy to the configuration as shown in this post, then pass the configuration to the Alamofire session. The rule is the same: the configuration must be complete before the session is created. On iOS 17 and later, a password set with applyCredential also applies in the Alamofire session, because it is part of the configuration.

Does the request go direct if the proxy fails?

Not with ProxyConfiguration. allowFailover defaults to false, and the request fails if the proxy is unreachable. On the older connectionProxyDictionary path, the request can go direct on some connection errors. Apple says this system is designed to make the request work. So always check the returned IP on the older path.

Ask ChatGPTAsk Claude