import Network
import WebKit

@available(iOS 17.0, macOS 14.0, *)
@MainActor
func makeWebView(username: String, password: String) -> WKWebView {
    let endpoint = NWEndpoint.hostPort(
        host: "proxy.example.net", port: 8080)
    let proxy = ProxyConfiguration(
        httpCONNECTProxy: endpoint, tlsOptions: nil)
    proxy.applyCredential(username: username, password: password)

    let store = WKWebsiteDataStore.nonPersistent()
    store.proxyConfigurations = [proxy]

    let configuration = WKWebViewConfiguration()
    configuration.websiteDataStore = store
    return WKWebView(frame: .zero, configuration: configuration)
}

The returned view uses a dedicated nonpersistent WKWebsiteDataStore. Load the intended website through that view. Use the intermediary's account or omit applyCredential for a proxy requiring none. For that unauthenticated HTTP branch, the HTTP proxy list provides candidate endpoints for the data store.

Every view sharing this store shares its proxy policy. This dedicated store also has ephemeral website data, so it does not inherit another view's existing website login.

Keep configuration ahead of navigation. WebKit warns that changing a store's proxy configuration can interrupt its current networking.

A separate URLSession fetch followed by loadHTMLString covers only that HTML fetch. Images, scripts and later navigation still use the view's networking; the store is the public hook for configuring that route.

Related articles