Skip to content

Instantly share code, notes, and snippets.

@cmoulton
Created June 29, 2016 16:46
Show Gist options
  • Save cmoulton/c26dc371d771c5cbaff325de6bbe5c77 to your computer and use it in GitHub Desktop.
Save cmoulton/c26dc371d771c5cbaff325de6bbe5c77 to your computer and use it in GitHub Desktop.
Alamofire Basic Auth
func doGetWithBasicAuthCredential() -> Void {
let username = "myUsername"
let password = "myPassword"
let credential = NSURLCredential(user: username, password: password, persistence: NSURLCredentialPersistence.ForSession)
Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(username)/\(password)")
.authenticate(usingCredential: credential)
.responseString { _, _, result in
if let receivedString = result.value
{
print(receivedString)
}
}
}
func printMyStarredGistsWithBasicAuth() -> Void {
let username = "myUsername"
let password = "myPassword"
let credentialData = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
let headers = ["Authorization": "Basic \(base64Credentials)"]
Alamofire.request(.GET, "https://api.github.com/gists/starred", headers: headers)
.validate()
.responseString { _, _, result in
if let error = result.error {
print(error)
}
if let receivedString = result.value {
print(receivedString)
}
}
}
@nguyentruongky
Copy link

Thanks. This solved my issue.

@sabbirahmed
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment