Skip to content

Instantly share code, notes, and snippets.

@iosdevzone
Last active September 19, 2015 11:09
Show Gist options
  • Save iosdevzone/4d11180bd46e9a38c7fd to your computer and use it in GitHub Desktop.
Save iosdevzone/4d11180bd46e9a38c7fd to your computer and use it in GitHub Desktop.
Minimal Basic Authentication Demo. Paste into playground & replace username and password. You must be on GitHub for this to work.
import Foundation
let username = "username"
let password = "password"
let base = "https://api.github.com"
let user = "\(base)/user"
let url = NSURL(string: user)
let request = NSMutableURLRequest(URL: url!)
let authString = "\(username):\(password)"
let authData = authString.dataUsingEncoding(NSUTF8StringEncoding)
let basic = String(data:authData!.base64EncodedDataWithOptions(NSDataBase64EncodingOptions(rawValue: 0)),
encoding: NSUTF8StringEncoding)
request.setValue("Basic \(basic!)", forHTTPHeaderField: "Authorization")
var response : NSURLResponse? = nil
do {
let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
print(String(data:data, encoding:NSUTF8StringEncoding))
}
catch let e {
print(e)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment