stay in a viewcontroller

1

I'm doing a login for iOS . The problem is that I have 2 viewController , of which, the first has 2 textField (username and password) and a button (Enter), and the second, only has a label Ingresaste and both connected by a Segue .

The first viewController has this code:

@IBAction func ingresarButton(_ sender: Any) {

    let txtcorreo = correoText.text!
    let txtclave = claveText.text!
    let url = URL(string: "webservice")
    let postString = "txtcorreo=\(txtcorreo)&txtclave=\(txtclave)"
    var request = URLRequest(url: url!)
    request.httpMethod = "POST"
    request.httpBody = postString.data(using: String.Encoding.utf8)
    let tarea = URLSession.shared.dataTask(with: request){
        (datos, respuesta, error) in
        if error != nil{
            print(error!)
        }else{
            do{
                let json = try JSONSerialization.jsonObject(with: datos!, options: .mutableContainers) as! [String:Any]
                let estado = json["estado"] as! Int

                if estado == 200 {
                    UserDefaults.standard.set(true, forKey: "usuarioLogueado")
                    UserDefaults.standard.synchronize()
                    self.performSegue(withIdentifier: "loginSegue", sender: self)
                }else{
                    print("usuario no existe")
                    self.dismiss(animated: true, completion: nil)
                }

            }catch{
                print("No funciona JSON")
            }
        }
    }
    tarea.resume()
}

The problem is that each time the fields are filled erroneously the second viewController appears for 5 seconds and then returns to the first one.

How can I do so that the second viewController does not appear when I fill in the wrong fields and only show me a message of User does not exist ?

    
asked by Dennis Mauricio Avilés Odar 05.06.2017 в 04:31
source

3 answers

0

If you have connected the Segue from the Button, as mentioned by jdev maybe it is what is giving you problems ... I recommend that you connect from the viewcontroller icon to create the Segue ... as in the image then I have pointed to the icon and then you leave Press ctrl and place it in the VC you want .. greetings!

    
answered by 15.06.2017 в 00:59
0

You could use a function like this, which adds a code block which waits until the HTTP query is completed and then proceeds with the following functions depending on the response obtained:

private func login_Servidor()
    {
        let postString = "txtcorreo=Usuario" +
                         "&txtclave=Clave"

        self.login(parametros: postString)
        { codigo_respuesa in

            if let codigo = codigo_respuesa
            {
                if codigo == 200
                {
                    DispatchQueue.main.async
                    {
                        UserDefaults.standard.set(true, forKey: "usuarioLogueado")
                        UserDefaults.standard.synchronize()
                        self.performSegue(withIdentifier: "loginSegue", sender: self)
                    }
                }
                else
                {
                    print("Usuario no existe")
                    DispatchQueue.main.async
                    {
                        self.dismiss(animated: true, completion: nil)
                    }
                }
            }
            else
            {
                print("No se logro completar la operacion")
            }
        }
    }

    private func login(parametros: String,
                       completion: @escaping(Int?) -> ())
    {
        var codigo_respuesta: Int?

        var request = URLRequest(url: URL(string: "webservice")!)
        request.httpMethod = "POST"
        request.httpBody = parametros.data(using: String.Encoding.utf8)

        URLSession.shared.dataTask(with: request)
        {(datos, respuesta, error) in

            if error != nil
            {
                print(error?.localizedDescription ?? "Error")
            }
            else
            {
                if let url_response = respuesta as? HTTPURLResponse
                {
                    if url_response.statusCode == 200
                    {//Operacion exitosa
                        do
                        {
                            let json = try JSONSerialization.jsonObject(with: datos!,
                                                                        options: .mutableContainers) as! NSDictionary
                            if let estado = json["estado"] as? Int
                            {
                                if estado == 200
                                {
                                    codigo_respuesta = estado
                                }
                            }
                        }
                        catch
                        {
                            print("No se pudo convertir el JSON")
                        }
                    }
                    else
                    {//Error en la consulta HTTP
                        print("El servidor envio un codigo de respuesa: \(url_response.statusCode)")
                    }
                }
            }
            completion(codigo_respuesta)
        }.resume()
    }
    
answered by 08.12.2017 в 19:00
0

Your button must be connected to the segue, what you must do is connect the ViewController (not the button), when calling the button to do the validation and only in case it is correct to call the Segue.

You should also take that dismiss, since now, by not going to the other screen you would try to dismiss the first ViewController.

You should also make sure you are not doing the screen in the main thread, since you are going to leave the app pasted.

And finally, as a tip, do not make requests from the ViewController, create a class for this, it will be easier to maintain or replace it.

    
answered by 08.06.2018 в 22:56