Created
February 12, 2017 22:06
-
-
Save Bunn/0eec1bdc6ee7732c06b6a67f660a37a0 to your computer and use it in GitHub Desktop.
Swift 3.0 HTTP Basic Authentication on Playground
This file contains 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 | |
func authenticate () { | |
//Credentials | |
let username = "USERNAME" | |
let password = "PASSWORD" | |
let loginString = "\(username):\(password)" | |
let loginData = loginString.data(using: String.Encoding.utf8)! | |
let base64LoginString = loginData.base64EncodedString() | |
//Request | |
let url = URL(string: "https://api.github.com")! | |
var request = URLRequest(url: url) | |
request.httpMethod = "GET" | |
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization") | |
//Fix "Failed to obtain sandbox extension" | |
URLCache.shared = URLCache(memoryCapacity: 0, diskCapacity: 0, diskPath: nil) | |
//Setup Session | |
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in | |
guard let responseData = data, | |
error == nil, | |
let jsonObject = try? JSONSerialization.jsonObject(with: responseData, options: []) else { | |
print("Error") | |
return | |
} | |
if let json = jsonObject as? [String : Any] { | |
print(json) | |
} | |
PlaygroundPage.current.finishExecution() | |
} | |
task.resume() | |
} | |
authenticate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment