I try to make an http request to a server protected by basic http authentification in swift for an app targeting iOS 10.3.
I try to had the authentification header to my request :
var request = URLRequest(url: URL(string: "https://my.webservice.url")!)
request.setValue("Basic my_auth_header", forHTTPHeaderField: "Authorization")
NSLog("headers = %@", request.allHTTPHeaderFields!)
let task = URLSession.shared.dataTask(with: mutableRequest, completionHandler: {data, response, error -> () in
do {
let httpResponse = response as! HTTPURLResponse
NSLog("response code %i", httpResponse.statusCode)
}
})
In the log, i can see my header before the request,but i always get a 401 status code.
In the documentation about url request i read that some header are reserved and should not be modify, these headers include Authorization
.
I try to implement URLSessionDelegate
in particular the function urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
.
But i do not have any clue how to create a credential for basic http authentification.
So my question is, how to handle basic http authentification in swift ?