Force running order Swift 3/Xcode 8 - Threads

Asked

Viewed 180 times

0

Hello, I’m new to Swift and this week I came across a problem that is already making me pull my hair out!
What happens is this, I divided in my application in several classes to make my code more "tidy" and in this wave I decided to divide some functions into classes by the project, but so far so good.
The problem is how Swift handles the execution queues, putting everything that’s not in my Viewcontroller in the background, which is getting in my way. I’m going to show you a little bit of code so you can extend what I’m saying better

The function of my Viewcontroller button:

    @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 native of Swift to give priority to interface, which makes everything fluid, but my problem is that my function 'Fadbaws.search' is never executed and so never returns a valid value.
How to prioritize my code only to continue after performing this function?
How to deal with Dispatchqueue on Swift?
From now on, thank you!

  • 1

    You will need to use a callback as a parameter in your method searchAluno. I suggest to give a search on callback on swift.

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 'searchAluno' function is finished, the 'complete' function is executed

Browser other questions tagged

You are not signed in. Login or sign up in order to post.