我需要一个带代理的NSURLSession,因为我必须实现它的
public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {}
委托加载我自己的CA证书的方法。
我还想用dataTaskWithURL
与completionHandler
打电话,因为我在调用的方法中将completionHandler
作为闭包参数。
public func call(hostName:String, completion: (responsedata : NSData?, response : NSURLResponse?, error : NSError?) -> Void){
let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
sessionConfiguration.HTTPCookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
sessionConfiguration.timeoutIntervalForRequest = 8;
let session = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
let requestURL = NSURL(string:"https://myhost.com/call")
session.dataTaskWithURL(requestURL!, completionHandler: completion).resume()
}
问题是只有在请求超时或失败时才会调用completionHandler
。如果成功,它永远不会被调用。有谁知道为什么?
我的completionHandler代码:
call("myhost.com", completion: {
(responsedata : NSData?, response : NSURLResponse?, error : NSError?) in
var newConnectionStatus: Bool
if let httpResponse = response as? NSHTTPURLResponse{
if error == nil {
if (httpResponse.statusCode == 200)
{
newConnectionStatus = true
}
else
{
newConnectionStatus = false
}
}
else{
newConnectionStatus = false
}
}else{
newConnectionStatus = false
}
if newConnectionStatus != scpGlobalVariables.sharedInstance().currentConnectivityStatus{
scpGlobalVariables.sharedInstance().currentConnectivityStatus = newConnectionStatus
NSNotificationCenter.defaultCenter().postNotificationName("ConnectionStateChangedNotification", object: self, userInfo: ["connectivityStatus":NSNumber(bool: newConnectionStatus)])
}
if newConnectionStatus == true{
sleep(5)
self.runConnectionChecker()
}else{
sleep(0);
self.runConnectionChecker()
}
})
只有在调用completionHandler时,response
和responsedata
为零