0

I'm trying to fetch data from a website via a command line utility in swift. I'm using NSURLConnection for this. Like so:

private let queue = NSOperationQueue.mainQueue()

NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: url), queue: queue) { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        println("Hello")
}

But the application stops running before the callback is called. How do I keep the application running so it won't exit early? I found CFRunLoop() and have added that in my main file. Now the application doesn't terminate. But I still don't get a response.

The same project in a playground with XCPSetExecutionShouldContinueIndefinitely does work however. So the problem does not lie in the NSURLConnection code.

Matthijn
  • 3,126
  • 9
  • 46
  • 69
  • 1
    Does this help http://stackoverflow.com/a/25126900/1187415 ? – Martin R Nov 28 '14 at 11:52
  • private let queue = NSOperationQueue.mainQueue() - added to example. – Matthijn Nov 28 '14 at 12:16
  • I have tried it with dispatch_main() and with NSRunLoop as in the referenced answer, and that worked for me. – Martin R Nov 28 '14 at 12:17
  • The comment or Martin R contains the solution. Adding [dispatch_main()](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/dispatch_main.3.html) to the end of my main function. `Programs must call dispatch_main() at the end of main() in order to process blocks submitted to the main queue.` – Matthijn Nov 28 '14 at 12:20

0 Answers0