Swift - Windows 身份验证的 NSURLSession

Swift - NSURLSession for Windows Authentication

我有这个 class 在这里和 class 里面是一个方法,我正在尝试在需要 API 的 URL 上做一个 NSURLSession 22=]认证用户名和密码。我已经按照这里的教程 https://gist.github.com/n8armstrong/5c5c828f1b82b0315e24

并想出了这个:

let webservice = "https://api.com"

let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let urlSession = NSURLSession(configuration: config)

class WebService: NSObject {

    func loginUser(username: String, password: String) -> Bool {

        let userPasswordString = "username@domain.com:Password"
        let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding)
        let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions([])
        let authString = "Basic \(base64EncodedCredential)"

        config.HTTPAdditionalHeaders = ["Authorization" : authString]

        let requestString = NSString(format:"%@", webservice) as String
        let url: NSURL! = NSURL(string: requestString)

        let task = urlSession.dataTaskWithURL(url) {
            (let data, let response, let error) in
            if (response as? NSHTTPURLResponse) != nil {
                let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print(dataString)
            }
        }

        task.resume()

        return true

    }

}

但是当我 运行 这时我收到 401 错误:401 - 未经授权:由于凭据无效,访问被拒绝。

我已经确认 URL 到 API 是正确的。与用户名和密码相同。我做错了什么?

我通过执行以下操作解决了这个问题:

var credential: NSURLCredential!

    func loginUser(username: String, password: String) -> Bool {

        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)

        credential = NSURLCredential(user:username, password:password, persistence: .ForSession)

        let requestString = NSString(format:"%@", webservice) as String
        let url: NSURL! = NSURL(string: requestString)

        let task = session.dataTaskWithURL(url, completionHandler: {
            data, response, error in

            dispatch_async(dispatch_get_main_queue(),
            {

                if(error == nil)
                {
                    print("Yay!")
                }
                else
                {
                    print("Naw!")
                }

            })

        })

        task.resume()

        return true

    }

然后添加 NSURLSessionDelegate 方法:

func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {

        if challenge.previousFailureCount > 0
        {
            completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
        }
        else
        {
            completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust:challenge.protectionSpace.serverTrust!))
        }

    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {

        completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential,credential)

    }