Skip to content

Instantly share code, notes, and snippets.

@maltekrupa
Last active September 10, 2021 05:18
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maltekrupa/71ae8b6bf89d33c5ad101dfbae2fc3d9 to your computer and use it in GitHub Desktop.
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

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

URLCredentialStorage.shared is a singleton.

@sbohmann
Copy link

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

ghost commented Sep 10, 2021

how to decode data / show response to user

Copy link

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