Skip to content

Instantly share code, notes, and snippets.

@jferrao
Last active November 8, 2015 23:17
Show Gist options
  • Save jferrao/740faa7bc98d31b9d0a1 to your computer and use it in GitHub Desktop.
Save jferrao/740faa7bc98d31b9d0a1 to your computer and use it in GitHub Desktop.
Sandbox test for a GET HTTP request on OSX
import Foundation
import XCPlayground
func httpGet(request: NSURLRequest!, callback: (NSURLResponse?, String, String?) -> Void) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
(data, response, error) -> Void in
if error != nil {
callback(response, "", error!.localizedDescription)
} else {
let result = NSString(data: data!, encoding:
NSASCIIStringEncoding)!
callback(response, result as String, nil)
}
}
task.resume()
}
var request = NSMutableURLRequest(URL: NSURL(string: "https://httpbin.org/get")!)
request.HTTPMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Accept")
httpGet(request){
(response, data, error) -> Void in
if error != nil {
print(error)
} else {
let httpResponse = (response as? NSHTTPURLResponse)
print(httpResponse?.statusCode)
print(httpResponse?.allHeaderFields)
print(response?.MIMEType)
print(data)
}
}
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment