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)