Swift 3 - Wait for Server Result

How could I wait for the server to return the result and only then execute another function (which will use the data from the server response).

Something like:

Func A: I get a response from the server: responseCode = 200, which is stored in the "code" variable Func B: check if the "code" variable is 200.

I can't find a way, and so far I always run func B before running it.

Many thanks.

 @IBAction private func bt_signin () {
    print("Step 1")
    func_a(text: url_text)
    func_b()
}


private func func_a(text: String) {

print("Step 2")

let url = NSURL(string: text)
let request = NSMutableURLRequest(url: url! as URL)

let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in
    guard error == nil && data != nil else
    {
        print("Error: ", error)
        return
    }

    let httpStatus = response as? HTTPURLResponse

    if httpStatus!.statusCode == 200
    {
        self.responseCode = httpStatus!.statusCode
        print("Step 3")                
    }
}
task.resume()
}

 func func_b (){
    print("Step 4")
    if (responseCode == 200) {
        print("Step 5")
    }
    }

      

I get the following:

Step 1
Step 2
Step 4
Step 3

      

+3


source to share


3 answers


You can use Closer to achieve this, make the following changes



@IBAction private func bt_signin () {
        print("Step 1")
        func_a(text: "") { (isSuccess) in
           self.func_b()
        }
    }


    private func func_a(text: String , _ completion:@escaping (_ isSuccess:Bool)->Void) {

        print("Step 2")

        let url = NSURL(string: text)
        let request = NSMutableURLRequest(url: url! as URL)

        let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in
            guard error == nil && data != nil else
            {
                print("Error: ", error)
                DispatchQueue.main.async {
                   completion(false)
                }

                return
            }

            let httpStatus = response as? HTTPURLResponse

            if httpStatus!.statusCode == 200
            {
                self.responseCode = httpStatus!.statusCode
                DispatchQueue.main.async {
                    completion(false)
                }
                print("Step 3")
            }
        }
        task.resume()
    }

    func func_b (){
        print("Step 4")
        if (responseCode == 200) {
            print("Step 5")
        }
    }

      

+3


source


You need to put func_b in the closure of func_a

...
if httpStatus!.statusCode == 200
{
    self.responseCode = httpStatus!.statusCode 
    print("Step 3")
    self.func_b                
}

      



This way func_b will run after the code returns. You can read more about closure online. I would recommend this video to start

0


source


Function Task running asynchronously will not wait for the result of tasks.so use main thread as below

DispatchQueue.main.async { 
   if httpStatus!.statusCode == 200
   {
       self.responseCode = httpStatus!.statusCode
       print("Step 3")        
       func_b()        // here call wanna perform any UI updates 
   }
}

      

You can also use a completion handler like @Irshad Ahmed's code

0


source







All Articles