Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

nguyentruongky commented Apr 4, 2018

Thanks. This solved my issue.

@sabbirahmed
Copy link

sabbirahmed commented Mar 26, 2020

Thanks

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