I need to send two objects to a web service so that I can respond in swift

1

I'm doing an application in swift 3 xcode 8 and they tell me that in order for me to access the web service I need to send two objects, it sends me the following example in ajax, how can I do it with xcode 8?

$("#cargar").click(function() {

    /*datosRegistro = {
        'user'      :   $("#user").val(),
        'pass'      :   $("#pass").val()
    };*/

    Datos = {
        "usr_username"  :   "usuario",
        "usr_password"  :   "contrasenia"    
    };

    datosRegistro = {
        "Accion"    :   2 , //2  es obligatorio para login
        "Datos"     :   Datos   
    };

    $.ajax({
        url: 'http://mihost/server/sitio.php',
        data: {'datosRegistro': JSON.stringify(datosRegistro) },
        type: 'POST',
        dataType: 'json',
        async: false,
        success: function(p, estado, xhr) {
            // Para atrapar otros posibles errores
            try {
                // Asigna el objeto de retorno
                objRetorno = JSON.parse(p);

                // Valida el error controlado
                if ( objRetorno.Error == true ) {
                    // Informa el error al usuario
                    // Muestra el mensaje (cambia icono y pone mensaje)
                    alert(objRetorno.Mensaje);

                    // Termina el procedimiento
                    return false;
                }
                else
                {

                    //aqui escribes el codigo en caso de ser correctos los datos

                    return true;
                }
            }
            catch(error){
                // Notifica el error al usuario
                alert( "Excepcion encontrada al recuperar cadena JSON.\n\nDetalles : " + error.message ) ;
            }  

        },
        error: function(xhr, estado, errata) {
            // Informa el error interno al usuario
            alert('La accion no pudo ser procesada correctamente...');

            // Termina el procedimiento
            return false;
        },
        dataType:   'html'

    }); // Termina la llamada AJAX
})
    
asked by oare77 22.02.2017 в 00:42
source

3 answers

0

The safest thing is that you have a URL to which to make the request, such as

link and here you have to build the chain with the parameters that they ask for but you have to tell the administrators how to pass them.

If for example you are passing Id but they are trying to validate in your webservice how iduser is going to fail you.

The URL will have to be built as for example: link (I would advise you to pass the variables in lowercase, instead of Id as you have to pass id). Anyway you will have to ask them how the comrade commented how you have to provide them with the data: if they search for a variable by name "idusuario" and you pass "id" it will always fail, but it is something that you have to clarify them;)

    
answered by 22.02.2017 / 12:27
source
1
  

... they tell me that in order for me to access the web service I need to send two objects

EDIT:

I modify the question by expanding some details.

(a). THE WEB SERVICE

Swift sends a request to the web service through a URL and it returns the JSON. When you receive it, you treat it (parsear) in Swift, as explained in (b).

For the web service to return, for example, this:

{
        "usr_username"  :   "victor.ramirez",
        "usr_password"  :   "victor"    
    }

You must know how to build your URL, that will tell you who manages the web service. In your case, an example (imaginary) of URL would be:

http://sipot.conanp.gob.mx/server/pasaportes.php?id=878&otro=otroparametro

As you see, you send two parameters to the web service separated by &, it receives it and uses them to consult the data you want and it returns a correct JSON and if not another erroneous one.

You can even test if the web service returns what you expect, by putting the URL in any browser. If you type something like this in your browser: https://reqres.in/api/users/1 you will get this result that you can see on the screen:

    {
    "data": {
        "id": 1,
        "first_name": "george",
        "last_name": "bluth",
        "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"
    }
}

Look at the elegance of the URL. Through it, what is asked of the web service is that it gives you the user's data whose id = 1.

In your case, an elegant or friendly URL would be: http://sipot.conanp.gob.mx/server/pasaportes/usuario/878 in which you ask for the passport data of the user whose id = 878. But as I said before, this depends on the web service programmer. The important thing is that it works well, send the data you request and it's up to you to process them.

(b). Manage the data received from the web service (or api) in Swift

Once your data is received, in this case a JSON, you manage it in Swift. In this example the JSON is stored within the variable parsedData .

Example:

let urlString = "http://tu.url.com"

let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
  if error != nil {
    print(error)
  } else {
    do {

      let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
      let usrName= parsedData["usr_username"] as! [String:Any]

      print(usrName)

      let usrPassword = parsedData["usr_password"] as! [String:Any]
      print(usrPassword)
    } catch let error as NSError {
      print(error)
    }
  }

}.resume()

This can be very useful: Apple Help on Swift

    
answered by 22.02.2017 в 01:08
0

When I make the request, the web service responds:

{"Error": true, "Message": "you are trying to hack us, or you did not send the information correctly", "Account": 0, "Data": null}

and the person in charge of the web service tells me that he answers me because I'm not sending him data and I'm not sending him well. Therefore, I do not know how to do it in swift, it tells me that I have to send objects like the ones I mentioned earlier. But I do not know if that can be done with swift. Thank you very much for your help.

    
answered by 22.02.2017 в 04:51