2017-05-13 34 views
1

我正在使用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) 


} 

的问题,我有:

  1. 如果我使用上面的代码,因为它是,我得到

    错误:“传递非逃逸参数‘completionHander’的功能期待的@逃脱关闭“

  2. 如果我让函数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的闭包语法委托授权挑战。

回答

1

在我看来你的问题的缺失部分是在Authhandler.handleChallenge完成处理程序是否逃跑。这是正确的?

taskDidReceiveChallengeWithCompletion completionHandler无法转义。所以你试图弄清楚如何让它在不被允许逃跑时逃脱。

大约3个月前,他们将completionHandler改为@escaping!请看这里:https://github.com/Alamofire/Alamofire/commit/b03b43cc381ec02eb9855085427186ef89055eef

你需要在PR合并后更新到Alamofire的版本,或者你需要弄清楚如何以完全不转义的方式处理completionHandler。意思是,你的Authhandler.handleChallenge不能有逃脱的completionHandler。