URLSession ne fonctionne pas avec URLCredential
j'ai une API à laquelle j'essaie de me connecter et le serveur est une authentification Windows.
je suis en train d'utiliser URLSession avec URLCredential avec le délégué méthodes
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void){
        var disposition: URLSession.AuthChallengeDisposition = URLSession.AuthChallengeDisposition.performDefaultHandling
        var credential:URLCredential?
        print(challenge.protectionSpace.authenticationMethod)
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
            if (credential != nil) {
                disposition = URLSession.AuthChallengeDisposition.useCredential
            }
            else
            {
                disposition = URLSession.AuthChallengeDisposition.performDefaultHandling
            }
        }
        else
        {
            disposition = URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge
        }
        completionHandler(disposition, credential);
    }
ce code fonctionne deux fois comme après avoir fait une certaine impression est parce qu'il y a deux méthodes D'authentification:
Nurlauthenticationmethodservertrust et Nslauthenticationmethodntlm when it runs through the Nslauthenticationmethodservertrust everything is fine, but when it runs NSURLAuthenticationMethodNTLM je reçois une erreur sur cette ligne:
credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
en disant ceci:
fatal error: unexpectedly found nil while unwrapping an Optional value
mais seulement quand je change de cette condition de
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM {
Qu'est-ce que je fais de mal?
Voici la méthode que j'utilise pour essayer de me connecter à cette API
func loginUser(_ username: String, password: String, completion: @escaping (_ result: Bool) -> Void)
    {
        //Create request URL as String
        let requestString = String(format:"%@", webservice) as String
        //Covert URL request string to URL
        guard let url = URL(string: requestString) else {
            print("Error: cannot create URL")
            return
        }
        //Convert URL to URLRequest
        let urlRequest = URLRequest(url: url)
        print(urlRequest)
        //Add the username and password to URLCredential
        credentials = URLCredential(user:username, password:password, persistence: .forSession)
        print(credentials)
        //Setup the URLSessionConfiguration
        let config = URLSessionConfiguration.default
        //Setup the URLSession
        let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
        //Prepare the task to get data.
        let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
            DispatchQueue.main.async(execute: {
                print(error!)
                if(error == nil)
                {
                    completion(true)
                }
                else
                {
                    completion(false)
                }
            })
        })
        //Run the task to get data.
        task.resume()
    } 
                1 réponses
Dans le  documentation Apple pour URLProtectionSpace.serverTrust, il dit:
nil si la méthode d'authentification de l'espace de protection n'est pas la confiance du serveur.
ainsi, vous essayez de déballer une valeur optionnelle de
dans votre cas, vous pourriez probablement remplacer la fonction entière par (non testé):
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void){
    var disposition: URLSession.AuthChallengeDisposition = URLSession.AuthChallengeDisposition.performDefaultHandling
    print(challenge.protectionSpace.authenticationMethod)
    if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
        disposition = URLSession.AuthChallengeDisposition.performDefaultHandling
    }
    else
    {
        disposition = URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge
    }
    completionHandler(disposition, credential);
}