I wanted to experiment with using NSURLSession to get RSS data, to see what that would look like. I wrote a chunk of code in a Playground, and when that didn't work I gutted the completion handler code and put in a print("hello, world") to verify the block was getting run.
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithURL(NSURL(string:"http://apod.nasa.gov/apod.rss")!, completionHandler:
{(data:NSData?, response:NSURLResponse?, error:NSError?) in
print("hello, world")
}
)!
task.resume()
In a Playground, nothing gets printed to the console. However I dropped this code into an Xcode project and it worked just fine. Why?
I ran into this issue as well while trying to play with NSURLSession. First and foremost, you need to import XCPlayground
, and call XCPSetExecutionShouldContinueIndefinitely()
. This will allow the code to be run asynchronously.
I can't tell you why exactly the print isn't working. All I know is, I was baffled by the same issue until I did a quick optional bind on the data (all the completion closure's parameters are optionals, mind you). For whatever reason, that works, and your print statement gets printed.
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
let task = session.dataTaskWithURL(NSURL(string:"http://apod.nasa.gov/apod.rss")!, completionHandler:
{(data:NSData?, response:NSURLResponse?, error:NSError?) in
if let data = data
{
print("hello, world")
}
}
)!
task.resume()
in Xcode 7.2 "XCPSetExecutionShouldContinueIndefinitely" is deprecated, now you can do the following:
import XCPlayground
//create instance of current playground page
let page = XCPlayground.XCPlaygroundPage
page.currentPage.needsIndefiniteExecution = true
//create your completion handler function
func completionHandlerFunction(callBack: (message: String, error: ErrorType?) -> Void){
callBack(message: "finish", error: nil)
}
//call the the completion handler function
completionHandlerFunction { (message, error) -> Void in
print(message) //output on the right side will be "finish\n"
//perform .finishExecution() on current page when block is executed
page.currentPage.finishExecution()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With