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
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
To resolve the "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." error, perform the following.
In info.plist, add key NSAppTransportSecurity as Dictionary with subkey NSAllowsArbitraryLoads as Boolean with value YES