当session
设置.init(configuration:..., delegate:self, delegateQueue:NSOperationQueue.mainQueue())
为代理服务器重定向时,NSURLSessionDataTask.resume()
不会导致执行task
. 当session
设置为.sharedSession()
时,task
按预期执行。
**kCFStreamPropertyHTTPProxyHost
等已被弃用。也许这会NSURLSessionConfiguration
以一种阻止执行的方式影响task
?
class ConnectionManager: NSURLSession, NSURLSessionDelegate {
.
.
.
if shouldUseProxy {
let proxyEnable = NSNumber(int: 1) as CFNumber
let proxyDict: [NSObject:AnyObject] = [
kCFNetworkProxiesHTTPEnable: proxyEnable,
kCFStreamPropertyHTTPProxyHost: proxyHost,
kCFStreamPropertyHTTPProxyPort: proxyPort,
kCFStreamPropertyHTTPSProxyHost: proxyHost,
kCFStreamPropertyHTTPSProxyPort: proxyPort,
kCFProxyTypeKey: kCFProxyTypeHTTPS,
kCFProxyUsernameKey: proxyUser,
kCFProxyPasswordKey: proxyPW
]
let config = NSURLSessionConfiguration.ephemeralSessionConfiguration()
config.connectionProxyDictionary = proxyDict
self.session = NSURLSession.init(configuration: config, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
} else {
self.session = NSURLSession.sharedSession()
}
self.task = self.session.dataTaskWithRequest(request) {
(data, response, error) in
if error == nil {
self.cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(response!.URL!)!
self.httpResponse = (response as? NSHTTPURLResponse)!
self.statusCode = (self.httpResponse!.statusCode)
guard error == nil && data != nil else {
print(error)
return
}
do {
if self.statusCode == 200 {
self.contentsOfURL = try NSString(contentsOfURL: self.URL, encoding: NSUTF8StringEncoding) as String
}
} catch {
}
}
}
self.task?.resume()
.
.
.
}