2017-05-13 37 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。