等待异步方法之后再进行筛选 [英] Wait for async method before segue

查看:100
本文介绍了等待异步方法之后再进行筛选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮,当我按下它时,我正在调用一个异步函数:

I have a button and when I press it I´m calling an Async function:

func check(url : String){
        let url = NSURL(string: url)
        print("Checking")
        dispatch_async(dispatch_get_main_queue(), {
            let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
                if error == nil {
                    self.isWorking = true
                }
                else{
                    self.isWorking = false
                    }
                }
            }
            task.resume()
        })
    }

因此,当我按下按钮时,我将执行以下操作:

So when I press my button I do the following:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!){
        let web = segue.destinationViewController as! ViewController()

        check(url)

        dispatch_async(dispatch_get_main_queue(), {
              if (isWorking){ 
                   // Do stuff
              }
      })
}

问题是在检查方法完成之前调用了isWorking.

The problem is that isWorking is called before the check method is completed.

在检查isWorking之前,如何确保检查已完成?

How can I make sure that check is completed before I make my check for isWorking?

推荐答案

您可以使用补全处理程序":

You could use a "completion handler":

func check(url : String, completion: (isWorking: Bool)->()) {
    let url = NSURL(string: url)
    print("Checking")
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        if error == nil {
            completion(isWorking: true)
        }
        else{
            completion(isWorking: false)
        }
    }
    task.resume()
}

您可以这样称呼它,并带有结尾的闭包:

And you call it like this, with a trailing closure:

check(url) { (isWorking) in
    if isWorking {
        // do stuff
    } else {
        // not working
    }
}

这篇关于等待异步方法之后再进行筛选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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