Swift Playgrounds are an invaluable tool for both learning Swift and exploring APIs. One thing that isn't obvious is by default, a playground will stop running when its top-level code is done. i.e. asynchronous code like this will not run like you expect:
import UIKit
var u = NSURL(string: "http://google.com")
var r: NSURLRequest = NSMutableURLRequest(URL: u!)
NSURLConnection.sendAsynchronousRequest(r,
queue: NSOperationQueue.currentQueue()!) { response, data, error in
NSLog("hello") //This wouldn't print
}
In order for it to work, add the following:
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely()
XCPSetExecutionShouldContinueIndefinitely()
keeps the playground running for as long as the timeline's timeout, which defaults to 30 seconds (configurable at the bottom of the playground)
.
.