Hello developers,
hope, someone can help me with authentication using NSURLSession. In the first of the two following code example, "didReceiveAuthenticationChallenge" never get's called. So I can't authenticate and get a "401 unauthorized". What am I doing wrong?
Thanks in advance,
Elmo 🙂
This doesn't work ("didReceiveAuthenticationChallenge" never get's called):
class ViewController: UIViewController, NSURLSessionDelegate {
override func viewDidLoad() {
super.viewDidLoad()
getData()
}
private var request: NSMutableURLRequest {
let baseUrl = "http://myRestCall....."
var url = NSURL(string: baseUrl)!
return NSMutableURLRequest(URL: url)
}
func getData() {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTaskWithRequest(request) {
(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
task.resume()
}
func URLSession(session: NSURLSession, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge)
{
println("didReceiveAuthenticationChallenge")
let user = "myUsername"
let password = "myPassword"
let credential = NSURLCredential(user: user, password: password, persistence: NSURLCredentialPersistence.ForSession)
challenge.sender.useCredential(credential, forAuthenticationChallenge: challenge)
}
}
The following code (with NSURLConnection) works fine (didReceiveAuthenticationChallenge" get's called):
class ViewController: UIViewController, NSURLConnectionDelegate{
override func viewDidLoad() {
super.viewDidLoad()
var conn = NSURLConnection(request: request, delegate: self, startImmediately: true)
}
private var request: NSMutableURLRequest {
let baseUrl = http://myRestCall ...
var url = NSURL(string: baseUrl)!
return NSMutableURLRequest(URL: url)
}
func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace) -> Bool
{
return true
}
func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge)
{
println("didReceiveAuthenticationChallenge")
let user = "myUsername"
let password = "myPassword"
let credential = NSURLCredential(user: user, password: password, persistence: NSURLCredentialPersistence.ForSession)
challenge.sender.useCredential(credential, forAuthenticationChallenge: challenge)
}
}