Skip to content

Instantly share code, notes, and snippets.

@jaylyerly
Created December 11, 2017 16:39
Show Gist options
  • Select an option

  • Save jaylyerly/6ce651ee22fc7adb14b1369b18acd2d2 to your computer and use it in GitHub Desktop.

Select an option

Save jaylyerly/6ce651ee22fc7adb14b1369b18acd2d2 to your computer and use it in GitHub Desktop.

Revisions

  1. jaylyerly created this gist Dec 11, 2017.
    38 changes: 38 additions & 0 deletions urlAuth.playground
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    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