我正在尝试与URLSession委托建立ssl连接,这是我收到的错误消息:
Objective-C方法'URLSession:didReceiveChallenge:completionHandler:'由方法提供'URLSession(:didReceiveChallenge:completionHandler :)'与可选的需求方法'URLSession(:didReceiveChallenge:completionHandler :)'冲突在协议'NSURLSessionDelegate'
func URLSession(session: NSURLSession,
didReceiveChallenge challenge:
NSURLAuthenticationChallenge,
completionHandler:
(NSURLSessionAuthChallengeDisposition,
NSURLCredential!) -> Void) {
let serverTrust: SecTrustRef = challenge.protectionSpace.serverTrust!
let serverCert: SecCertificateRef = SecTrustGetCertificateAtIndex(serverTrust, 0).takeUnretainedValue()
let serverKey: NSData = SecCertificateCopyData(serverCert).takeRetainedValue()
let bundle: NSBundle = NSBundle.mainBundle()
let mainbun = bundle.pathForResource("ca", ofType: "der")
let key: NSData = NSData(contentsOfFile: mainbun!)!
// let turntocert: SecCertificateRef =
// SecCertificateCreateWithData(kCFAllocatorDefault, key).takeRetainedValue()
if serverKey == key {
let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
challenge.sender!.useCredential(credential, forAuthenticationChallenge: challenge)
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential,credential)
}
else{
challenge.sender!.cancelAuthenticationChallenge(challenge)
completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
}
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: (NSURLRequest!) -> Void) {
var newRequest : NSURLRequest? = request
print(newRequest?.description);
completionHandler(newRequest)
}
答案 0 :(得分:2)
你现在使用Swift 2吗?我在更新到Swift 2时开始出现此错误。
我可以通过将其更改为:
来解决此问题func URLSession(session: NSURLSession,
task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?)
-> Void) {
// your code
}
答案 1 :(得分:1)
正确的方法签名是:
func URLSession(session: NSURLSession,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition,
NSURLCredential?) -> Void)
其中NSURLCredential参数必须是可选的(在可选值后面带问号(?))。