Created
February 19, 2016 21:33
-
-
Save redknitin/7027eeaddc7e05178331 to your computer and use it in GitHub Desktop.
Using NSURLSession for HTTP requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To run in the playground, the following code is needed: