Created
May 26, 2015 17:55
-
-
Save collinsrj/ae003be148cb584d426c to your computer and use it in GitHub Desktop.
ExampleHTTPSRequestInPlayground
This file contains 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
import UIKit | |
import XCPlayground | |
// Plain HTTP Request | |
var session = NSURLSession.sharedSession() | |
var url = NSURL(scheme: "http", host: "www.ibm.com", path: "/")! | |
var request = NSMutableURLRequest(URL: url) | |
var plainHttpTask = session.dataTaskWithRequest(request) { | |
(data, response, error) -> Void in | |
if error != nil { | |
// handle the error | |
println("Error: \(error)") | |
} else { | |
let stringData = NSString(data: data, encoding: NSUTF8StringEncoding) | |
} | |
} | |
plainHttpTask.resume() | |
// HTTPS Request | |
var secureSession = NSURLSession.sharedSession() | |
if let url = NSURL(scheme: "https", host: "api.github.com", path: "/users/collinsrj/repos") { | |
var httpsTask = secureSession.dataTaskWithURL(url) { | |
(data, response, error) -> Void in | |
if error != nil { | |
// handle the error | |
println("Error: \(error)") | |
} else { | |
let stringData = NSString(data: data, encoding: NSUTF8StringEncoding) | |
} | |
} | |
httpsTask.resume() | |
} | |
XCPSetExecutionShouldContinueIndefinitely() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note
You need to make sure you run this with Run in Full Simulator in the Playground Settings. If you don't you'll see an error "The certificate for this server is invalid..." I spent hours trying to figure out what was wrong. It's really hard to use Playgrounds to learn in if they don't work.