另一功能完成后再运行一个功能 [英] Running one function after another completes

查看:56
本文介绍了另一功能完成后再运行一个功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在pullData()完成之后运行loadViews(),我想知道这样做的最佳方法是什么?我也想在其上设置10秒超时,以便在可能的情况下显示网络错误.从我阅读的内容来看,GCD看起来是完成此任务的方法,但是我对它的实现感到困惑.感谢您提供的任何帮助!

I am trying to run loadViews() after the pullData() completes and I am wondering what the best way of doing this is? I would like to set a 10 sec timeout on it as well so I can display a network error if possible. From what I have read, GCD looks like it is the way to accomplish this but I am confused on the implementation of it. Thanks for any help you can give!

//1
pullData()
//2
loadViews()

推荐答案

您需要的是带有完成块的完成处理程序.

What you need is a completion handler with a completion block.

创建一个非常简单:

func firstTask(completion: (success: Bool) -> Void) {
    // Do something

    // Call completion, when finished, success or faliure
    completion(success: true)
}

并使用您的完成代码块,如下所示:

And use your completion block like this:

firstTask { (success) -> Void in
    if success {
       // do second task if success
       secondTask()
    }
}

这篇关于另一功能完成后再运行一个功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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