2015-01-23 12 views
10

Guardando oltre la documentazione di NSURLSession e NSURLSessionConfiguration, ho avuto l'impressione che dovrei configurarlo con un dizionario come il seguente:come aggiungere un proxy per un NSURLSession

// Create a dictionary to describe the proxy 
    NSDictionary *proxyDict = @{ 
     (NSString *)kCFProxyHostNameKey : @"myProxyHost.com", 
     (NSString *)kCFProxyPortNumberKey : @"12345", 
     (NSString *)kCFProxyTypeKey  : (NSString*)kCFProxyTypeHTTP 
    }; 

    // Create a configuration that uses the dictionary 
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; 
    [configuration setConnectionProxyDictionary:proxyDict]; 

Tuttavia, le richieste da parte NSURLSession creato con questa configurazione connettersi direttamente.

risposta

17

Si scopre, le chiavi del dizionario che si desidera sono le varianti Ruscello, sono quelli che risolvono fino a "httpProxy" e così via:

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]; 
+0

Grazie! Un milione di volte grazie! Non l'avrei mai capito. Certo sarebbe bello se Apple lo avesse documentato. – bugloaf

+0

Grazie mille! Sei un vero risparmiatore! –

+0

@Jeff - Ho provato questo .. Ma i dati che ritornano da '^ (dati NSData *, risposta NSURLResponse *, errore NSError *) restituiscono i risultati di myProxyHost.com e non di www.google.com Può aiutarmi –

6

Poiché molti di chiavi di risposta di Jeff sono stati deprecati Io uso questo quelli

NSMutableDictionary *proxy=[NSMutableDictionary dictionaryWithDictionary:@{(__bridge NSString *)kCFNetworkProxiesHTTPEnable : @1, (__bridge NSString *)kCFNetworkProxiesHTTPSEnable : @1}]; 
proxy[(__bridge NSString *)kCFNetworkProxiesHTTPProxy] =host; 
proxy[(__bridge NSString *)kCFNetworkProxiesHTTPSProxy]=host; 
proxy[(__bridge NSString *)kCFNetworkProxiesHTTPPort] =port; 
proxy[(__bridge NSString *)kCFNetworkProxiesHTTPSPort] =port; 
proxy[(__bridge NSString *)kCFProxyUsernameKey]=user; 
proxy[(__bridge NSString *)kCFProxyPasswordKey]=password; 

configuration.connectionProxyDictionary=proxy; 
7

Se qualcuno ha bisogno della versione rapida di questo:

Swift 3

valore
let sessionConfiguration = URLSessionConfiguration.default 
sessionConfiguration.connectionProxyDictionary = [ 
    kCFNetworkProxiesHTTPEnable as AnyHashable: true, 
    kCFNetworkProxiesHTTPPort as AnyHashable: 999, //myPortInt 
    kCFNetworkProxiesHTTPProxy as AnyHashable: "myProxyUrlString" 
] 
let session = URLSession(configuration: sessionConfiguration) 
+0

ho problemi con questo. anche se usato, l'ip della mia richiesta API è lo stesso usato senza proxy ... –

+0

http://stackoverflow.com/questions/42617582/how-to-use-urlsession-with-proxy-in-swift-3 –

4

kCFProxyPortNumberKey dovrebbe essere Int non String

1

Swift 3 estensione

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) 
1

Sulla base di tutte le risposte precedenti, questo funziona per Swift 4, sia HTTP e HTTPS:

let proxyHost = "127.0.0.1" 
let proxyPort = 8888 
let configuration = URLSessionConfiguration.default 
configuration.connectionProxyDictionary = [ 
    kCFNetworkProxiesHTTPEnable: true, 
    kCFNetworkProxiesHTTPProxy: proxyHost, 
    kCFNetworkProxiesHTTPPort: proxyPort, 
    kCFNetworkProxiesHTTPSEnable: true, 
    kCFNetworkProxiesHTTPSProxy: proxyHost, 
    kCFNetworkProxiesHTTPSPort: proxyPort 
] 

proxyHost deve essere un nome host e non contenere alcun schema URL.

Problemi correlati