How to add a HTTPS proxy to NSURLSession in SWIFT

2019-03-31 10:30发布

问题:

I have used the following code for connecting to the proxy server and works great for only HTTP requests but not for HTTPS. In iOS 9.0, kCFStreamPropertyHTTPSProxyHost and kCFStreamPropertyHTTPSProxyPort are depreciated.

let myPortInt = 12345;
let myProxyUrlString = "myProxyURL";

    let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration();
    sessionConfiguration.connectionProxyDictionary = [
        kCFNetworkProxiesHTTPEnable: true,
        kCFNetworkProxiesHTTPPort: myPortInt,
        kCFNetworkProxiesHTTPProxy: myProxyUrlString,
    ]
    let url = NSURL(string: endPointUrl)
    let postRequest = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10.0)


    let jsonString =  bodyString
    postRequest.HTTPBody = jsonString 
    postRequest.HTTPMethod = "POST"
    postRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

    let session = NSURLSession(configuration: sessionConfiguration)       
    let task = session.dataTaskWithRequest(postRequest){}

回答1:

I found the solution for adding HTTPS proxy to NSURLsession

   let proxyDict : NSDictionary = ["HTTPEnable": Int(1), "HTTPProxy": myProxyUrlString, "HTTPPort": myPortInt, "HTTPSEnable": Int(1), "HTTPSProxy": myProxyUrlString, "HTTPSPort": myPortInt]

    let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration();