Clicky

iOS Dev Nugget 131 Running Asynchronous Code in Swift Playgrounds

.

Need to run a code review on your codebase? Hire me

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)


.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues