Skip to content

Instantly share code, notes, and snippets.

@redknitin
Created February 19, 2016 21:33
Show Gist options
  • Select an option

  • Save redknitin/7027eeaddc7e05178331 to your computer and use it in GitHub Desktop.

Select an option

Save redknitin/7027eeaddc7e05178331 to your computer and use it in GitHub Desktop.
Using NSURLSession for HTTP requests
func funkytown() {
let request = NSMutableURLRequest(URL: NSURL(string: "http://www.cnn.com")!)
//request.HTTPMethod = "POST"
//let postString = "id=13&name=Jack"
//request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPMethod = "GET"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}
@redknitin
Copy link
Copy Markdown
Author

To run in the playground, the following code is needed:

import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

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