Home » Php » php – Unable to pushasync in iOS after Validation in MainPage

php – Unable to pushasync in iOS after Validation in MainPage

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a Cross-platform App in Xamarin, at the moment is working perfectly in Android, however, I’m now debugging it on iOS using iPhoneSimulator on Windows Computer (I’m Connected with MAC in Cloud Service).

I have put a stopping point on my Controller in the section where it does the consult in the Webservice and I do see that my Username and Password parameters are being filled with the information from the view (MainPage, or Logging Page).

My Current problem is that when I click on my access Button on the MainPage (which is my Logging Page), it doesn’t do anything it just stays there.

At the moment this is the Main Page XAML Code:

<Image Source="taber.png"
       FlexLayout.Order="-1"
       FlexLayout.AlignSelf="Center"
                   WidthRequest="180"
                   HeightRequest="180" Aspect="AspectFit" />

<Label>

</Label>
<Frame
CornerRadius="15"
Padding="0"
BackgroundColor="#507BF5"
Margin="15,10,15,10" 
HasShadow="False"
>
<Label 
Margin="5"
Text="Usuario" 
HorizontalOptions="Center" 
BackgroundColor="Transparent"
FontSize="Large" 
TextColor="White"
FontAttributes="Bold"
/>
</Frame>
<Frame
CornerRadius="15"
Padding="0"
Margin="15,10,15,10"
 >
    <Entry Placeholder="Usuario"
x:Name="txtUsuario"   
HorizontalTextAlignment="Center"
TextChanged="OnChangeUser"
/>
</Frame>
<Frame
CornerRadius="15"
Padding="0"
BackgroundColor="#507BF5"
Margin="15,10,15,10" 
HasShadow="False"
>
    <Label 
Margin="5"
Text="Contraseña" 
HorizontalOptions="Center" 
BackgroundColor="Transparent"
FontSize="Large" 
TextColor="White"
FontAttributes="Bold"
/>
</Frame>
<Frame
CornerRadius="15"
Padding="0"
Margin="15,10,15,10"
 >
<Entry IsPassword="True"
       Placeholder="Contraseña"
       x:Name="txtPassword"
       HorizontalTextAlignment="Center"
/>
</Frame>
<Label FlexLayout.Grow="1" />
<Button 
      BorderColor="#507BF5"
      BorderRadius="5"
      BorderWidth="2"
      Margin="15,10,15,10"
      x:Name="bntIngresar"
      Text="Ingresar"
      TextColor="White"
      Clicked="btnIngresar_click" 
      BackgroundColor="#507BF5"/>

I use the btnIngresar_click method to validate the information through the PHP Web service here is the Code behind in the XAML.CS for btnIngresar_click:

private async void btnIngresar_click(object sender, EventArgs e)
        {
            try
            {
                string input = txtPassword.Text;
                string encryptedPass;

                MD5 md5 = MD5.Create();
                byte[] inputBytes = Encoding.ASCII.GetBytes(input);
                byte[] hash = md5.ComputeHash(inputBytes);

                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hash.Length; i++)
                {
                    sb.Append(hash[i].ToString("X2"));
                }

                encryptedPass = sb.ToString();

                UseManager manager = new UseManager();
                var result = await manager.userLogin(txtUsuario.Text.ToString(), encryptedPass);

                if (result.Count() > 0)
                {
                    foreach (var nuser in result)
                    {
                        servidor = nuser.id_servidor;
                        acceso = nuser.id_acceso;
                        usuario = nuser.id;
                    }
                    //await Navigation.PushAsync(new Principal(servidor, acceso, usuario));
                    await Navigation.PushAsync(new SplashPage(servidor, acceso, usuario));
                }
                else
                {
                    await DisplayAlert("Error", "Usuario o Contraseña Incorrectos", "Accept", "Cancel");
                }
            }
            catch (Exception e1)
            {

            }
        }

Now here is the Method userLogin which takes me to the Web Service in PHP: (FYI as mentioned on top I put a Stop Point in the line: var result = await cliente.GetAsync(URL + “login.php?username=” + username + “&password=” + password); and I can see that the Username Variable is being captured and the Password one as well.)

 public async Task<IEnumerable<user>> userLogin(string username, string password)
        {
            HttpClient cliente = getClient();

            var result = await cliente.GetAsync(URL + "login.php?username=" + username + "&password=" + password);

            if (result.IsSuccessStatusCode)
            {
                var content = await result.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<IEnumerable<user>>(content);
            }
            return Enumerable.Empty<user>();
        }

Finally here is the Webservice in PHP:

<?php

$username= $_REQUEST['username'];
$password= $_REQUEST['password'];

$cnx=new PDO("mysql: host=localhost; dbname=securitb","DBUSERNAME","DBPASSWORD");
$res=$cnx->query("select * from usuarios where username ='$username' and password ='$password'");

$datos = array();

foreach ($res as $row){
    array_push($datos, array(
    'id' => $row['id'],
    'username' => $row['username'],
    'password' => $row['password'],
    'activo' => $row['activo'],
    'id_acceso' => $row['id_acceso'],
    'id_servidor' => $row['id_servidor'],
    ));
}
echo utf8_encode(json_encode($datos));
?>

Why it might be that my iOS app is not moving to the Splash Screen?

How to&Answers:
  1. First problem is that you are making multiple requests with your code:

    private HttpClient getClient()
    {
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Add("Accept", "application/json"); client.DefaultRequestHeaders.Add("Connection", "close");
        return client;
    }
    
  2. Personally I think that main problem is here:

        try
        {
            HttpClient cliente = getClient();
    
            var result = await cliente.GetAsync(URL + "login.php?username=" + username + "&password=" + password);
    
            if (result.IsSuccessStatusCode)
            {
                var content = await result.Content.ReadAsStringAsync();
                return JsonConvert.DeserializeObject<IEnumerable<user>>(content);
            }
            return Enumerable.Empty<user>();
        }
        catch (Exception)
        {
    
        }
    

    Try to catch here for exceptions. I think there is a problem with object deserialization.