我正在使用AF並使用它的委託來捕獲我的服務器返回的身份驗證挑戰。問題與Alamofire挑戰委託和轉義關閉
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’的功能期待的@逃脫關閉「
如果我讓函數handleAuthenticationSession的參數不轉義,我得到:
func handleAuthenticationforSession(_ challenge: URLAuthenticationChallenge, completionHandler: (Foundation.URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { }
錯誤:「閉合使用非逃逸參數‘完成’的可允許其逸出」
另外,從AuthHandler類handleChallenge方法(這是OBJ-C框架的一部分)的外表如下所示。
-(BOOL)handleChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition,
NSURLCredential *credential))completionHandler;
因此,基本上我陷入僵局,而我使用Alamofire的閉包語法委託授權挑戰。