0

I am trying my hand at using yts' API (https://yts.to/api) in a small command-line client. Therefore, I fetch a JSON file using a standard NSUrlSession with a dataTask.

func httpGet(request: NSURLRequest!, callback: (String, String?) -> Void) {
    var session = NSURLSession.sharedSession()
    var task = session.dataTaskWithRequest(request) {
        (data, response, error) -> Void in
        if error != nil {
            callback("", error.localizedDescription)
        } else {
            var result = NSString(data: data, encoding: NSASCIIStringEncoding)!
            callback(result, nil)
        }
    }
    task.resume()
}

To prevent the program from exiting before the file is loaded, I added GCD as by Wait until an asynchronous api call is completed - Swift/IOS.

var semaphore = dispatch_semaphore_create(0)
let adr = "https://yts.to/api/v2/list_movies.json"
var request = NSMutableURLRequest(URL: NSURL(string: adr)!)
httpGet(request) {
    (data, error) -> Void in
    dispatch_semaphore_signal(semaphore)
    if error != nil {
        println(error)
    } else {
        println(data)
    }
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)

This should keep the process running until httpGet finishes, or am I misunderstanding something? However, it never gets this far, instead interrupting quite soon:

{"status":"ok","status_messagProgram ended with exit code: 0

or

{"status":"ok","status_meProgram ended with exit code: 0

or anything similarly useless (the whole file is about 2 pages on a 200*50 terminal)

Community
  • 1
  • 1
5T41N
  • 3
  • 1

1 Answers1

1

You're signalling the semaphore complete before you finish printing the data. So then the wait exits and terminates your program. You can see that it was starting to print when it was interrupted.

Move dispatch_semaphore_signal(semaphore) to the end of the block.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610