Created
December 11, 2017 16:39
-
-
Save jaylyerly/6ce651ee22fc7adb14b1369b18acd2d2 to your computer and use it in GitHub Desktop.
Basic URL Auth with URLCredential
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
import UIKit | |
import PlaygroundSupport | |
// Test site for Basic Authentication | |
// substitute values in the path to auth against | |
// http://httpbin.org/basic-auth/user/passwd | |
// so | |
// http://httpbin.org/basic-auth/foo/bar | |
// would check for username = foo and password = bar | |
let url = URL(string: "http://httpbin.org/basic-auth/bob/123")! | |
let cred = URLCredential(user: "bob", | |
password: "123", | |
persistence: .forSession) | |
let protectionSpace = URLProtectionSpace(host: "httpbin.org", | |
port: 80, | |
protocol: "http", | |
realm: "Fake Realm", | |
authenticationMethod: NSURLAuthenticationMethodHTTPBasic) | |
URLCredentialStorage.shared.setDefaultCredential(cred, for: protectionSpace) | |
let task = URLSession.shared.dataTask(with: url) {(data, response, error) in | |
print("finish task") | |
if let error = error { | |
print("Error downloading url: \(error)") | |
} else { | |
let str = String(data: data!, encoding: .utf8) ?? "<???>" | |
print("data: >\(str)<") | |
print("response: >\(String(describing:response))<") | |
} | |
} | |
print("start task") | |
task.resume() | |
PlaygroundPage.current.needsIndefiniteExecution = true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment