Skip to content

Instantly share code, notes, and snippets.

@armstrongnate
Created July 20, 2014 21:45
Show Gist options
  • Star 66 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save armstrongnate/5c5c828f1b82b0315e24 to your computer and use it in GitHub Desktop.
Save armstrongnate/5c5c828f1b82b0315e24 to your computer and use it in GitHub Desktop.
HTTP Basic Authentication using NSURLSession in swift
import Foundation
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let userPasswordString = "username@gmail.com:password"
let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding)
let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions(nil)
let authString = "Basic \(base64EncodedCredential)"
config.HTTPAdditionalHeaders = ["Authorization" : authString]
let session = NSURLSession(configuration: config)
var running = false
let url = NSURL(string: "https://example.com/api/v1/records.json")
let task = session.dataTaskWithURL(url) {
(let data, let response, let error) in
if let httpResponse = response as? NSHTTPURLResponse {
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(dataString)
}
running = false
}
running = true
task.resume()
while running {
println("waiting...")
sleep(1)
}
@TimvdGaag
Copy link

👍 tnx

@Lutzmann
Copy link

Hallo is there a Update with Swift 3 ?

@igorzhukov
Copy link

How/where can I set http method (GET,POST)?

@anirudhsmarttechnica
Copy link

Hallo is there a Update with Swift 3 ?

@CPiersigilli
Copy link

It would be very useful for me to upgrade to Swift 3 ....

@megifernanda
Copy link

how to make get request json if i have token key and secret ?

@maltekrupa
Copy link

Hi,
I ported the code to Swift4 in XCode9 since this example wasn't working anymore.

https://gist.github.com/temal-/71ae8b6bf89d33c5ad101dfbae2fc3d9

@Satyam-sutapalli
Copy link

How to pass bearer token for all subsequent requests?

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