首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >URLSession不使用URLCredential

URLSession不使用URLCredential
EN

Stack Overflow用户
提问于 2016-12-06 15:46:17
回答 1查看 2.2K关注 0票数 9

我正在尝试连接一个API,服务器是Windows身份验证。

我试图将URLSession与URLCredential一起与委托方法一起使用

代码语言:javascript
复制
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);
    }

此代码运行两倍,因为有两种身份验证方法:

当NSURLAuthenticationMethodServerTrust和NSURLAuthenticationMethodNTLM在NSURLAuthenticationMethodServerTrust中运行时,一切都很好,但是当它运行NSURLAuthenticationMethodNTLM时,我在这一行中得到了一个错误:

代码语言:javascript
复制
credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)

他说:

代码语言:javascript
复制
fatal error: unexpectedly found nil while unwrapping an Optional value

但是,只有当我将这个条件从

代码语言:javascript
复制
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {

代码语言:javascript
复制
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM {

我做错什么了?

下面是我尝试连接到那个API的方法

代码语言:javascript
复制
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()

    } 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-17 14:04:08

URLProtectionSpace.serverTrust中,它说:

如果保护空间的身份验证方法不是服务器信任,则为零。

因此,您正在尝试打开nil的可选值,这当然会导致崩溃。

在您的示例中,您可能只需将整个函数替换为(未经测试):

代码语言:javascript
复制
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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40999371

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档