Asynchronous swift 3

梦想与她 提交于 2020-01-15 09:20:06

问题


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:

signIn()
getContacts()

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: "com.app.queue")

queue.async {
signIn()
getContacts()

}

回答1:


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: {
  getContacts()
}

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?




回答2:


You're looking for NSOperation. You can use NSOperation to chain operations together using dependencies. Once one operation complete's it can pass it's completion block to the next operation. An example for your use case might be:

// AuthOperation is a subclass of NSOperation
let signInOperation = AuthOperation()
// ContactsOperation  is a subclass of NSOperation
let getContactsOperation = ContactsOperation()

getContactsOperation.addDependency(signInOperation)

Ray Wenderlich has a great tutorial covering NSOperation. The tutorial uses a downloading operation to load images asynchronously with a dependency that will filter the photo upon completion of the network request.

There is also a great sample project by Apple that uses operations with asynchronous network requests.



来源:https://stackoverflow.com/questions/40385951/asynchronous-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!