Skip to content

Instantly share code, notes, and snippets.

@gjones
Created May 5, 2017 22:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gjones/00a7625dc39e5b676b557bf06d6c957c to your computer and use it in GitHub Desktop.
Save gjones/00a7625dc39e5b676b557bf06d6c957c to your computer and use it in GitHub Desktop.
JSON API with Basic Auth in Swift 3
func fetchResultsFromApi() {
let username = "username"
let password = "password"
let url = NSURL(string: "http://localhost:3000/api/v1/results.json")
let request = NSMutableURLRequest(url: url! as URL)
let config = URLSessionConfiguration.default
let userPasswordString = "\(username):\(password)"
let userPasswordData = userPasswordString.data(using: String.Encoding.utf8)
let base64EncodedCredential = userPasswordData!.base64EncodedString(options: [])
let authString = "Basic \(base64EncodedCredential)"
config.httpAdditionalHeaders = ["Authorization" : authString]
let session = URLSession(configuration: config)
let task = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
let httpResponse = response as! HTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("Everyone is fine, file downloaded successfully.")
} else {
print(statusCode)
}
}
task.resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment