Search code examples
iosswiftalamofiregrand-central-dispatch

Dispatch Group not allowing Alamofire request to execute


I'm using DispatchGroup to wait until a callback for one of my functions executes before continuing. Within that function, I'm calling Alamo fire get request. My issue occurs when I introduce the DispatchGroup, the AlamoFire closure never gets executed.

Sample

let group = DispatchGroup()

group.enter()
Networking.getInfo(userID: userID) { info in
    group.leave()
}

group.wait()

Networking class:

static func getInfo(userID: Int, completion: @escaping(_ info: String) -> Void) {
    // Program reaches here
    Alamofire.request("https://someurl.com").responseJSON { response in
        // Program does NOT get here
        if let json = response.result.value {
            completion("Successful request")
        } else {
            completion("Some Error")
        }
    }
}

When I don't use the DispatchGroup, it works fine. When I DO use the DispatchGroup, The getInfo function starts, but the closure of the Alamofire request never gets executed.


Solution

  • Not sure I'm right, but I suspect that the Alamofire response is being queued on the same queue (main) that the group has suspended (wait()). Because the queue is suspended, the completion closure never executes.

    Manually writing asynchronous code like this can be quite tricky. My suggestion would be to use any one of the asynchronous libraries out there which can help with this. My personal favourite being PromiseKit which also has specific extensions to support Alamofire. Projects like this can take a lot of the headache out of asynchronous code. They may take some time to get your head around their paradigms, but it's worth doing.