ayanonagon/talks

Does Alamofire actually work with scripts?

Opened this issue · 1 comments

I'm trying to make it work, using a basic sample, which is supposed to have JSON response.

Alamofire.request(.GET, "http://httpbin.org/get")
    .responseJSON { (_, _, JSON, _) in
        println("done")
        println(JSON)
    }

println("last")

When I run the script, it just exits and print nothing from network request, only the "last" bit is printed.

I suspect that's due to async behavior of Alamofire. Do I have to do additional synchronization myself to make sure the script doesn't exit before n/w response gets back?

In scripts, you (most likely) want to turn the asynchronous behavior in synchronous behavior. I.e. you want the request to complete before the next line of code is executed.
However, you should not block the main run loop, or the request will never complete (at least in my experience).
I found a working solution using something like this:

var done = false
Alamofire.request(.GET, "http://httpbin.org/get")
    .responseJSON { (_, _, JSON, _) in
        println("done")
        println(JSON)
        done = true
    }

while !done {
    NSRunLoop.currentRunLoop().runUntilDate(NSDate(timeIntervalSinceNow: 0.5))
}
println("last")