Created
May 5, 2017 22:39
-
-
Save gjones/00a7625dc39e5b676b557bf06d6c957c to your computer and use it in GitHub Desktop.
JSON API with Basic Auth in Swift 3
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
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