How to programmatically add a proxy to an NSURLSession

前端 未结 6 1243
醉酒成梦
醉酒成梦 2020-12-01 05:02

Looking over the documentation of NSURLSession and NSURLSessionConfiguration, I was under the impression I should configure it with a dictionary li

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 05:26

    Swift 3 extension

    extension URLSession {
    
        func withProxy(proxyURL: String, proxyPort: Int) -> URLSession {
    
            var configuration = self.configuration
    
            configuration.connectionProxyDictionary = [
                kCFNetworkProxiesHTTPEnable as AnyHashable : true,
                kCFNetworkProxiesHTTPPort as AnyHashable : proxyPort,
                kCFNetworkProxiesHTTPProxy as AnyHashable : proxyURL
            ]
    
            return URLSession(configuration: configuration, delegate: self.delegate, delegateQueue: self.delegateQueue)
        }
    }
    

    Usage:

    let session = URLSession().withProxy(proxyURL: "xxxxxx", proxyPort: 8321)
    

提交回复
热议问题