Last active
July 1, 2016 15:21
-
-
Save joshavant/196dd41d62783b5fd0f7751027dec699 to your computer and use it in GitHub Desktop.
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
// 1. Implement URLSession:task:didReceiveChallenge:completionHandler:. (Be sure to call the completion handler with NSURLSessionAuthChallengeDisposition.PerformDefaultHandling and a nil NSURLCredential.) | |
// 2. Set a breakpoint in the callback + trigger an authentication challenge at runtime | |
// 3. In the debugger, inspect the callback's `challenge.protectionSpace` argument for the values to put in the following lines of code... | |
// 4. Put the following lines of code somewhere before your network requests (i.e. AppDelegate area, or other) | |
let basicAuthCredentials = NSURLCredential(user: "username", password: "password", persistence: .Permanent) | |
let foobarHttpsProtectionSpace = NSURLProtectionSpace(host: "foo.bar.com", port: 443, protocol: "https", realm: "This Probably Has A Value, Get It From The Delegate Callback", authenticationMethod: NSURLAuthenticationMethodHTTPBasic) | |
NSURLCredentialStorage.sharedCredentialStorage().setDefaultCredential(basicAuthCredentials, forProtectionSpace: apidevHttpsProtectionSpace) | |
// 5. Remove the delegate callback implementation. The credentials stored in the `sharedCredentialStorage` will be used, when required. |
I feel like I've found a long-buried treasure!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tip: Don't create + store lots of unnecessary
NSURLProtectionSpace
s (i.e. one for http/80, one for the main domain, etc). From my own experience trying this, they can quietly cause conflicts with each other, leaving you wondering why nothing is working.Instead, obtain exactly the necessary
NSURLProtectionSpace
information needed from the callback function, and implement only those.Also, if you're connecting to the host over HTTPS, the first authentication challenge will be
NSURLAuthenticationMethodServerTrust
. Ignore that one (that's for SSL). The next one -NSURLAuthenticationMethodHTTPBasic
- is the one you're looking for.