Skip to content

Instantly share code, notes, and snippets.

@maltekrupa
Last active September 10, 2021 05:18
Show Gist options
  • Select an option

  • Save maltekrupa/71ae8b6bf89d33c5ad101dfbae2fc3d9 to your computer and use it in GitHub Desktop.

Select an option

Save maltekrupa/71ae8b6bf89d33c5ad101dfbae2fc3d9 to your computer and use it in GitHub Desktop.
HTTP Basic Authentication using URLSession and URLCredentialStorage in swift 4 with xcode 9
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let credential = URLCredential(user: “username@gmail.com”, password: “password”, persistence: URLCredential.Persistence.forSession)
let protectionSpace = URLProtectionSpace(host: "example.com", port: 443, protocol: "https", realm: "Restricted", authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
URLCredentialStorage.shared.setDefaultCredential(credential, for: protectionSpace)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: "https://example.com/api/v1/records.json")!
let task = session.dataTask(with: url) { (data, response, error) in
guard error == nil else {
print(error?.localizedDescription ?? "")
return
}
print(String(data: data!, encoding: .utf8))
}
task.resume()
@SylvainRX
Copy link
Copy Markdown

I'm not sure I understand how the lines 6,7,8 have any impact on what comes after. Can you explain, please?

@sbohmann
Copy link
Copy Markdown

URLCredentialStorage.shared is a singleton.

@sbohmann
Copy link
Copy Markdown

There are German double end quotes (upper double quotes) in the code snippet, creating really bad swift compilation errors. Such a good idea to allow arbitrary unicode in names...

Copy link
Copy Markdown

ghost commented Sep 10, 2021

how to decode data / show response to user

Copy link
Copy Markdown

ghost commented Sep 10, 2021

plz anyone answer urgent

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment