Skip to content

Instantly share code, notes, and snippets.

@armstrongnate
Created July 20, 2014 21:45
Show Gist options
  • Select an option

  • Save armstrongnate/5c5c828f1b82b0315e24 to your computer and use it in GitHub Desktop.

Select an option

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)
}
@OlivierAlbertini
Copy link
Copy Markdown

thx dude !

@ajonno
Copy link
Copy Markdown

ajonno commented Feb 7, 2015

ditto ! thanks

@raleydotcom
Copy link
Copy Markdown

you are a god! I have been looking all over for this.

@teameh
Copy link
Copy Markdown

teameh commented Mar 23, 2015

Tnx! 👍

@ishulai
Copy link
Copy Markdown

ishulai commented May 28, 2015

Found this after looking for about two hours. You legend.

Copy link
Copy Markdown

ghost commented Aug 20, 2015

Thank you very much for this gist.

Using Xcode 7 beta 5 (Swift 2), base64EncodedStringWithOptions(nil) gives an error "Cannot invoke 'base64EncodedStringWithOptions' with an argument list of type '(nil)'"

but the following worked for me:
let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue:0))

@vermont42
Copy link
Copy Markdown

This gist and kenl97216's comment are examples of why I love Github.

@getSwiftly
Copy link
Copy Markdown

Finally this worked!

@rayraj
Copy link
Copy Markdown

rayraj commented Apr 15, 2016

@n8armstrong:
Everyone seemed to like your code. Question: what does your main thread/code do during your while loop? i.e. what is experienced by the user during the process of waiting for url response
thanks

@HometownRocker
Copy link
Copy Markdown

rayraj the session data task is an asynchronous network call. If there is not a loop waiting for a network response the code would immediately execute to normal completion. The network response is received by the completionHandler of the session data task. The user sees "waiting..." in the console log until the completionHandler prints out a dataString and resets the loop condition for normal completion.

@expresado
Copy link
Copy Markdown

You are my hero. Thank you for this solution. Nice, clear, working.

@Radovan1
Copy link
Copy Markdown

Thank you! This help saved me :)

@TimvdGaag
Copy link
Copy Markdown

👍 tnx

@Lutzmann
Copy link
Copy Markdown

Hallo is there a Update with Swift 3 ?

@igorzhukov
Copy link
Copy Markdown

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

@anirudhsmarttechnica
Copy link
Copy Markdown

Hallo is there a Update with Swift 3 ?

@CPiersigilli
Copy link
Copy Markdown

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

@megifernanda
Copy link
Copy Markdown

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

@maltekrupa
Copy link
Copy Markdown

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
Copy Markdown

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