Skip to content

Instantly share code, notes, and snippets.

@jaylyerly
Created December 11, 2017 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaylyerly/6ce651ee22fc7adb14b1369b18acd2d2 to your computer and use it in GitHub Desktop.
Save jaylyerly/6ce651ee22fc7adb14b1369b18acd2d2 to your computer and use it in GitHub Desktop.
Basic URL Auth with URLCredential
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