Force execution order Swift 3 / Xcode 8 - Threads

0

Hello, I'm new to swift and this week I came across a problem that is already making me pull out my hair! What happens is the following, divided in my application in several classes to leave my code more "straightened" and in this wave I decided to divide some functions into classes by the project, but until then everything ok. The problem is how Swift handles the execution queues, leaving behind everything that is not in my ViewController, which is hindering me. I'll show you some of the code so you can better extend what I'm saying.

The function of the button of my ViewController:

    @IBAction func btnLogin(_ sender: UIButton) {

    //Eis a linha que o swift "pula"
    let dadosAlunoWS = FadbaWS.buscaAluno(matricula: MatriculaTbox.text!, senha: SenhaTbox.text!, token: "TOKEN")  

    //'dadosAlunoWS' será sempre vazio porque 'FadbaWS.buscaAluno' 
    //só é executada ao fim de 'btnLogin'

    if dadosAlunoWS.sucesso && dadosAlunoWS.usuarioEncontrado{
        print(dadosAlunoWS.nome)

    }else{ 

        //Erro na requisição
    }        
}

I know the concept of parallelism and competition and researching I could realize that it is Swift's native to prioritize the interface, which makes everything fluid, but my problem is that my 'FadbaWS.buscaAluno' function is never executed and so never returns a valid value.
How do I prioritize my code only to continue after performing this function? How to deal with the DispatchQueue in Swift? Thanks in advance!

    
asked by anonymous 07.02.2017 / 22:06

1 answer

1

To solve my problem, I used a CompletionHandler

       self.FadbaWS.buscaAluno(matricula: MatriculaTbox.text!, senha: SenhaTbox.text!, token: "TOKEN", complete:{ resultado in

      if resultado.2 && resultado.3{
        print(resultado.0)
      }else 
        //Error on request
      }
   })

In my case, I needed some parameters, so I did it like this:

    func buscaAluno(matricula: String, senha: String, token: String, complete: @escaping (_ nome: String?, _ login: String?, _ sucesso:Bool, _ userok:Bool) -> Void) {

    complete("Wender", "1234", true, true)

  }
}

When my 'lookup' function is finished, the 'complete' function is executed

    
15.02.2017 / 01:45