How to programmatically add a proxy to an NSURLSession
It turns out, the dictionary keys you want are the Stream variants, they are the ones that resolve down to "HTTPProxy" and such:
NSString* proxyHost = @"myProxyHost.com";
NSNumber* proxyPort = [NSNumber numberWithInt: 12345];
// Create an NSURLSessionConfiguration that uses the proxy
NSDictionary *proxyDict = @{
@"HTTPEnable" : [NSNumber numberWithInt:1],
(NSString *)kCFStreamPropertyHTTPProxyHost : proxyHost,
(NSString *)kCFStreamPropertyHTTPProxyPort : proxyPort,
@"HTTPSEnable" : [NSNumber numberWithInt:1],
(NSString *)kCFStreamPropertyHTTPSProxyHost : proxyHost,
(NSString *)kCFStreamPropertyHTTPSProxyPort : proxyPort,
};
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
configuration.connectionProxyDictionary = proxyDict;
// Create a NSURLSession with our proxy aware configuration
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
// Form the request
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com?2"]];
// Dispatch the request on our custom configured session
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"NSURLSession got the response [%@]", response);
NSLog(@"NSURLSession got the data [%@]", data);
}];
NSLog(@"Lets fire up the task!");
[task resume];
How to use URLSession with Proxy in Swift 3
I think the working (supposed to be deprecated) keys are:
kCFStreamPropertyHTTPSProxyHost
kCFStreamPropertyHTTPSProxyPort
Could you try this code?
func makeRequestViaUrlSessionProxy(_ url: String, completion: @escaping (_ result: String?) -> ()) {
let request = URLRequest(url: URL(string: url)!)
let config = URLSessionConfiguration.default
config.requestCachePolicy = URLRequest.CachePolicy.reloadIgnoringLocalCacheData
config.connectionProxyDictionary = [AnyHashable: Any]()
config.connectionProxyDictionary?[kCFNetworkProxiesHTTPEnable as String] = 1
config.connectionProxyDictionary?[kCFNetworkProxiesHTTPProxy as String] = "142.54.173.19"
config.connectionProxyDictionary?[kCFNetworkProxiesHTTPPort as String] = 8888
config.connectionProxyDictionary?[kCFStreamPropertyHTTPSProxyHost as String] = "142.54.173.19"
config.connectionProxyDictionary?[kCFStreamPropertyHTTPSProxyPort as String] = 8888
let session = URLSession.init(configuration: config, delegate: nil, delegateQueue: OperationQueue.current)
let task = session.dataTask(with: request) {
(data: Data?, response: URLResponse?, error: Error?) in
if error != nil {
NSLog("Client-side error in request to \(url): \(error)")
completion(nil)
return
}
if data == nil {
NSLog("Data from request to \(url) is nil")
completion(nil)
return
}
let httpResponse = response as? HTTPURLResponse
if httpResponse?.statusCode != 200 {
NSLog("Server-side error in request to \(url): \(httpResponse)")
completion(nil)
return
}
let encodingName = response?.textEncodingName != nil ? response?.textEncodingName : "utf-8"
let encoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding(encodingName as CFString!))
let stringData = String(data: data!, encoding: String.Encoding(rawValue: UInt(encoding)))
session.invalidateAndCancel()
completion(stringData)
}
task.resume()
}
Also please make sure your proxy server is configured to handle https requests.
Note: It might give deprecated
warning for those keys but keys are still working (see https://forums.developer.apple.com/thread/19356#131446)
how to authenticate the proxy in urlsession?
URLSessionConfiguration
need additional headers.
let configuration.httpAdditionalHeaders = ["Proxy-Authorization": Request.authorizationHeader(user: "user", password: "password") ]
Handling redirects with custom NSURLProtocol and HTTP proxy
It turned out the problem was with the redirection for an HTTPS server, while there is no HTTPS proxy defined. To use HTTPS proxy, the code should looks like:
config.connectionProxyDictionary = @
{
@"HTTPEnable":@YES,
(id)kCFStreamPropertyHTTPProxyHost:@"1.2.3.4",
(id)kCFStreamPropertyHTTPProxyPort:@8080,
@"HTTPSEnable":@YES,
(id)kCFStreamPropertyHTTPSProxyHost:@"1.2.3.4",
(id)kCFStreamPropertyHTTPSProxyPort:@8080
};
Source: How to programmatically add a proxy to an NSURLSession
Related Topics
Xcode 8/Swift 3: "Expression of Type Uiviewcontroller? Is Unused" Warning
How to Know That If the Only Visible Area of a .Png Is Touched in Xcode
Pass Parameter in Webservice in Swift
Xcode6: Run Two Instances of the Simulator
Dial Ussd Code from iPhone Programmatically
How to Add a Container View Programmatically
How to Handle iPhone Screen Sizes/Resolution for Background Images
If No Table View Results, Display "No Results" on Screen
iOS Swift Multiple Dimension Arrays - Compiliing Takes Ages. What Should I Change
Didreceiveremotenotification: Fetchcompletionhandler: Open from Icon VS Push Notification
How to Disable the Network in iOS Simulator
Disable Autolayout Constraint Error Messages in Debug Console Output in Xcode
Fixing Xcode 9 Issue: "iPhone Is Busy: Preparing Debugger Support for Iphone"
iOS Avfoundation: Setting Orientation of Video
Horizontal Uiscrollview Inside Custom Uitableviewcell - Using Ib Storyboard - Not Scrolling