Last active
September 10, 2021 05:18
-
-
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
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 Foundation | |
import PlaygroundSupport | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
let credential = URLCredential(user: “[email protected]”, 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() |
URLCredentialStorage.shared is a singleton.
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...
how to decode data / show response to user
plz anyone answer urgent
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm not sure I understand how the lines 6,7,8 have any impact on what comes after. Can you explain, please?