异步Swift 3 [英] Asynchronous swift 3

查看:93
本文介绍了异步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:

signIn()
getContacts()

我想确保只有在登录完成后才调用getContacts. FWIW,我无法编辑方法签名,因为它们来自Google SDK.

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.

这是我尝试过的:

let queue = DispatchQueue(label: "com.app.queue")

queue.async {
signIn()
getContacts()

}

推荐答案

就其性质而言,异步调用不会运行到完成状态,然后再调用下一个.在要求他们完成任务之前,他们会立即返回.

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提供了一个很好的解决方案:使用一对NSOpration,并使它们彼此依赖.您还可以将这两个操作放入一个串行队列中,而第二个操作要等到第一个操作完成后才能开始.

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.

但是,如果这些调用在另一个线程上触发了异步操作,它们可能仍会返回,并且操作队列可能会触发第二个操作(getContacts()调用,而无需等待signIn()完成.

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()
}

第三个选择是设计一个带有委托的登录对象,登录完成后,登录对象将在委托上调用signInComplete方法.

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.

这是一件很平常的事情,大多数网络API都是为即开即用"而构建的.如果Google API没有处理此问题的功能,我会感到震惊.

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.

您使用的是什么Google框架?您可以指向它的文档吗?

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

这篇关于异步Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆