0

I copy-pasted the first example of the Alamofire readme (at fa3c6d0) into main.swift:

import Foundation
import Alamofire

Alamofire.request("https://httpbin.org/get").responseJSON { response in
    print(response.request)  // original URL request
    print(response.response) // HTTP URL response
    print(response.data)     // server data
    print(response.result)   // result of response serialization

    if let JSON = response.result.value {
     print("JSON: \(JSON)")
    }
}

print("Done")

When I run this, all I get is Done, then the application terminates.

While I see here that I can pick a dispatch queue, this answer seems to suggest that I shouldn't have to.

Anyway, having had a similar issue with "basic" requests I tried the same solution but to no avail: the application now blocks. So, apparently, Alamofire has a different default than URLSession and wants to use the main thread.

What is the best way to have a request executed (and waited for) in an application like this?

Community
  • 1
  • 1
Raphael
  • 9,779
  • 5
  • 63
  • 94
  • I received an answer [here](https://github.com/Alamofire/Alamofire/issues/1111#issuecomment-281480598) but have not had time to check it out yet. – Raphael Feb 24 '17 at 11:04

1 Answers1

0

We need to do two things.

  1. Execute the request in the background.
  2. Block the main thread until the request is done, i.e. the completion handler ran.

My original code does neither.

The first item is achieved by using .response(queue: DispatchQueue(label: "some-name")) (or one of its variants).

Waiting can be done in several ways.

  1. Using a flag and active waiting, as shown here (won't scale to more than one request).
  2. Use active waiting with countdown latch as shown here (works for multiple requests).
  3. Use DispatchSemaphore as seen e.g. here.

And probably many more.

Community
  • 1
  • 1
Raphael
  • 9,779
  • 5
  • 63
  • 94