Swift 3 - Wait for the server result

0

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

Something like:

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

I can not find the way and so far I always execute the function B before it worked A ends.

Thank you very much.

So far I have tried the following:

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


private func func_a(text: String) {

    print("Paso 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("Paso 3")                
        }
    }
    task.resume()
}

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

And on the screen I get the following:

Paso 1
Paso 2
Paso 4
Paso 3
    
asked by DavidGP 13.07.2017 в 10:51
source

1 answer

0

For this you can use closures. Apple Documentation

An example taking your code and executed in a playground:

func do_a(text: String, completion: (Void) -> Void) {
  print("Paso 1")
  // tu codigo
  print("Paso 2")
  // tu codigo
  print("Paso 3")
  // tu codigo
  completion() // Ejecutas el closure
}

func do_b(){
  print("Paso 4")
  // tu codigo
  print("Paso 5")
}

do_a(text: "Hola", completion: { do_b() })

// Resultado
// Paso 1
// Paso 2
// Paso 3
// Paso 4
// Paso 5

Basically the first function receives the second function as a parameter.

    
answered by 13.07.2017 / 23:34
source