4

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?

PopKernel
  • 4,110
  • 5
  • 29
  • 51
  • Possible duplicate of [How to print to console using swift playground?](http://stackoverflow.com/questions/24003092/how-to-print-to-console-using-swift-playground) – Martin R Jun 22 '15 at 20:26

3 Answers3

1

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()
Canucklesandwich
  • 693
  • 6
  • 15
1

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()
}
dan
  • 873
  • 8
  • 11
0

This worked for me when I was trying to print from inside a URL completionHandler:

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

...

URLSession.shared.dataTask(with: url, completionHandler: {

 ..

}).resume()
Mike R
  • 4,448
  • 3
  • 33
  • 40