Skip to content

Instantly share code, notes, and snippets.

@Bunn
Created February 12, 2017 22:06
Show Gist options
  • Save Bunn/0eec1bdc6ee7732c06b6a67f660a37a0 to your computer and use it in GitHub Desktop.
Save Bunn/0eec1bdc6ee7732c06b6a67f660a37a0 to your computer and use it in GitHub Desktop.
Swift 3.0 HTTP Basic Authentication on Playground
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