Last active
October 6, 2021 07:33
-
-
Save algal/e91f6b02a37c4aaeaa16f609de69c16e to your computer and use it in GitHub Desktop.
HTTP Basic Authentication in iOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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