Skip to content

Instantly share code, notes, and snippets.

@algal
Last active October 6, 2021 07:33
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save algal/e91f6b02a37c4aaeaa16f609de69c16e to your computer and use it in GitHub Desktop.
Save algal/e91f6b02a37c4aaeaa16f609de69c16e to your computer and use it in GitHub Desktop.
HTTP Basic Authentication in iOS
/*
Everyone on Stack Overflow does HTTP Basic Authentication on iOS by manually
building the HTTP headers.
This amounts to re-implementing HTTP.
Why? The Cocoa Touch URL Loading System aleady knows HTTP, and you can
configure your URLSession to supply HTTP Basic Authentication credentials
like so.
Be warned: this example configures the session to use the given credentials on all
requests, which is probably not what you want.
A better and more authoritative answer from Quinn: https://forums.developer.apple.com/thread/68809
*/
class HTTPBasicAuthenticationSessionTaskDelegate : NSObject, URLSessionTaskDelegate {
let credential:URLCredential
init(user:String,password:String) {
self.credential = URLCredential(user: user, password: password, persistence: URLCredential.Persistence.forSession)
}
func urlSession(_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(.useCredential,credential)
}
}
let delegate = HTTPBasicAuthenticationSessionTaskDelegate(user:username,password:password)
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: delegate, delegateQueue: nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment