我正在使用AF并使用它的委托来捕获服务器返回的身份验证质询。
func connectGetRequest(_ url : URL){
let sessionManager = Alamofire.SessionManager.default
sessionManager.request(url).responseString { response in
print("Response String: (response.result.value)")
}
let delegate: Alamofire.SessionDelegate = sessionManager.delegate
delegate.taskDidReceiveChallengeWithCompletion = { session, task, challenge, completionHander in
print("session is (session), task is (task) challenge is (challenge.protectionSpace.authenticationMethod) and handler is (completionHander)")
if(challenge.protectionSpace.authenticationMethod == "NSURLAuthenticationMethodServerTrust"){
completionHander(.performDefaultHandling,nil)
}else{
print("challenge type is (challenge.protectionSpace.authenticationMethod)")
// Following line give me the error: "passing non-escaping parameter 'completionHander' to function expecting an @escaping closure"
self.handleAuthenticationforSession(challenge,completionHandler: completionHander)
}
}
delegate.dataTaskDidReceiveData = {session , task, data in
print("received data (data)")
}
}
func handleAuthenticationforSession(_ challenge: URLAuthenticationChallenge,completionHandler: @escaping (Foundation.URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
Authhandler.handleChallenge(forURLSessionChallenge: challenge, completionHandler: completionHandler)
}
我有的问题:
如果我按原样使用上面的代码,我会得到
错误:"将非转义参数'completionHander'传递给期望@escaping闭包的函数">
如果我使函数句柄身份验证会话的参数不转义,我会得到:
func handleAuthenticationforSession(_ challenge: URLAuthenticationChallenge, completionHandler: (Foundation.URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { }
错误:"关闭使用非转义参数'完成'可能允许它转义">
此外,来自AuthHandler类(obj-c框架的一部分(的handleChallenge方法如下所示。
-(BOOL)handleChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,
NSURLCredential *credential))completionHandler;
所以基本上当我使用 Alamofire 的闭包语法来委派身份验证挑战时,我陷入了僵局。
您的问题中缺少的部分是Authhandler.handleChallenge
中的完成处理程序是否正在转义。是吧?
但是taskDidReceiveChallengeWithCompletion
完成处理程序是非转义的。所以你试图弄清楚当它不被允许逃脱时如何让它逃脱。
查看 Alamofire 源代码,大约 3 个月前,他们将 completeHandler 更改为 @escaping!看这里: https://github.com/Alamofire/Alamofire/commit/b03b43cc381ec02eb9855085427186ef89055eef
在 PR 合并后,您需要更新到 Alamofire 版本,或者您需要弄清楚如何以完全非转义的方式处理 completionHandler。这意味着,您的Authhandler.handleChallenge
不能具有转义的 completionHandler。