如何顺序执行两个异步函数

时间:2016-02-22 10:54:46

标签: ios swift asynchronous dispatch

func getTopicIdFromMYSQL(){
    let myUrl = NSURL(string: "xxxx")
    let request = NSMutableURLRequest(URL: myUrl!)
    request.HTTPMethod = "POST"
    let email:String = "xxx@gmail.com"
    let postString = "email=\(email)"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data, response, error in
        if(error != nil){

            print("Get all topic")
            print("error=\(error)")
            return
        }
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

            if let parseJSON = json
            {
                let resultValue = parseJSON["status"] as? String

                print("Get all topic")
                favouriteTopic = parseJSON["getResult"]! as! [AnyObject]
                print("return topic:\(favouriteTopic)")

                dispatch_async(dispatch_get_main_queue(), {

                    if(resultValue == "Success"){

                    }
                    else{
                        let error = UIAlertController(title: "Error", message: "Please check your network configuration!:-(", preferredStyle: .Alert)
                        let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
                        let ok = UIAlertAction(title: "OK", style: .Default, handler: nil)
                        error.addAction(cancel)
                        error.addAction(ok)
                    }
                })

            }

        }catch
        {
            print(error)
        }

    }
    task.resume()

} 我已经有了这个代码,但是我想在它之后运行另一个函数。我该怎么办。像:

getTopicIdFromMYSQL()
getCommentFromMYSQL()
print("Finish")

我发现问题是我的代码没有按顺序执行,函数getCommentFromMYSQL与getTopicIdFromMYSQL几乎相同,我想运行这三个以便我该怎么办?

3 个答案:

答案 0 :(得分:3)

将完成处理程序作为参数添加到异步函数中:

func getTopicIdFromMYSQL(completion: (AnyObject?, ErrorType?)->())

func getCommentFromMYSQL(completion: (AnyObject?, ErrorType?)->())

注意: 异步函数完成时,最终必须最终调用完成处理程序 - 无论是错误还是计算值。

然后调用这些函数,如下所示:

getTopicIdFromMYSQL() { (result1, error) in
    if let result1 = result1 {
        // process result1
        // ...
        getCommentFromMYSQL() { (result2, error) in
            if let result2 = result2 {
                // process result2
                // ...
            } else {
                // handle error
            }
        }
    } else {
        // handle error
    }
}

您可以按如下方式实现这些功能:

func getTopicIdFromMYSQL(completion: (AnyObject?, ErrorType?) {
    let myUrl = NSURL(string: "xxxx")
    let request = NSMutableURLRequest(URL: myUrl!)
    request.HTTPMethod = "POST"
    let email:String = "xxx@gmail.com"
    let postString = "email=\(email)"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data, response, error in
        if error != nil {
            completion(nil, error)
        }
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
            if let parseJSON = json {
                let resultValue = parseJSON["status"] as? String
                print("Get all topic")
                favouriteTopic = parseJSON["getResult"]! as!  [AnyObject]
                completion(favouriteTopic, nil)
            } else {
                throw MyError.Error(message: "bogus JSON")
            }    
        } catch let error { 
            completion(nil, error)
        }
    }
    task.resume()
}

答案 1 :(得分:0)

代码始终按顺序执行。我认为你的问题是你在这行中进行异步调用:

NSURLSession.sharedSession().dataTaskWithRequest(request)

但是,由于代码是按顺序执行的,因此在异步调用完成之前调用方法getCommentFromMYSQL()。你应该在这个条件中调用getCommentFromMYSQL()

if (resultValue == "Success") {
}

或者随时随地。这将确保在第一个方法完成执行后调用方法getCommentFromMYSQL()

答案 2 :(得分:0)

这是因为,您正在进行异步调用,它在后台线程中运行。

如果希望按顺序执行它们,请在调度到主队列后调用下一个方法

public class Copy extends Original implements Listener {

    @Override
    public void somethingHappened() {
        // Implement code here
    }
}