Search code examples
iosswiftasynchronousdispatch

How to execute two asynchronous functions sequentially


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

} I have already got this code, how ever, I want to run another function after it. What should I do. like:

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

I find the problem is my code does not excute in order, the function getCommentFromMYSQL is almost the same as getTopicIdFromMYSQL, I want to run these three in order what should I do?


Solution

  • Add a completion handler to your asynchronous functions as a parameter:

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

    Note: The completion handler must be eventually called when the asynchronous function completes - either with an error or the computed value.

    You then call these functions as shown below:

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

    You may implement these functions as follows:

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