JP Aquino JP Aquino - 1 year ago 151
Swift Question

Asynchronous swift 3

I need to make an asynchronous call so that the second method is only called after the first one is completed.Both methods are network calls. Something like this:


I want to make sure that getContacts only gets called after the signIn is completed. FWIW, I can't edit the methods signatures because they are from a Google SDK.

This is what I tried:

let queue = DispatchQueue(label: "")

queue.async {


Answer Source

Async calls, by their nature, do not run to completion then call the next thing. They return immediately, before the task they were asked to complete has even been scheduled.

You need some method to make the second task wait for the first to complete.

NauralInOva gave one good solution: use a pair of NSOprations and make them depend on each other. You could also put the 2 operations into a serial queue and the second one wouldn't begin until the first is complete.

However, if those calls trigger an async operation on another thread, they may still return and the operation queue may trigger the second operation (the getContacts() call without waiting for signIn() to complete.

Another option is to set up the first function to take a callback:

signIn( callback: {

A third option is to design a login object that takes a delegate, and the login object would call a signInComplete method on the delegate once the signIn is complete.

This is such a common thing to do that most networking APIs are built for it "out out of the box." I'd be shocked if the Google API did not have some facility for handling this.

What Google framework are you using? Can you point to the documentation for it?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download