Running RunLoop-Based Async Code in Swift Playgrounds
Published in
1 min readMar 30, 2016
By default, Swift Playgrounds do not execute (asynchronous) code that depends on the RunLoop for callbacks or completion.
This includes, for example , NSURLConnection/Session requests, and NSTimer actions.
This is because, the code in the Playground is executed, and the process is terminated — the completion operations / callbacks are simply not executed.
To enable this, there are two options
Use the XCPlayground API
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true // Your Code
This creates a 30-second window for the async code to execute and finish, after which it’ll time-out. This duration can be customised using the timeline view (at the bottom of the playground). After the code is executed, you can call:
XCPlaygroundPage.currentPage.finishExecution()
Run an NSRunLoop yourself.
NSRunLoop.currentRunLoop().runUntilDate(NSDate().dateByAddingTimeInterval(30))