2017-05-17 1 views
0

J'essaye de faire un appel asynchrone à un webservice. Je voudrais faire cet appel lors de l'ouverture de l'application (App.xaml.cs). Selon la réponse qui me revient, il doit naviguer vers une page particulière Mais je ne travaille pas.Xamarin Forms http async request

public partial class App : PrismApplication 
{ 
    public App(IPlatformInitializer initializer = null) : base(initializer) { } 

    protected override void OnInitialized() 
    { 
     InitializeComponent(); 
     try 
     { 
      CheckLogin().Wait(); 


     } 
     catch (Exception e) 
     { 
      var t = e; 
     } 
    } 
    private static async Task CheckLogin() 
    { 


     try 
     { 
      var login = new Login 
      { 
       Email = "[email protected]", 
       Password = "test", 
      }; 
      var client = new HttpClient { BaseAddress = new Uri("http://www.api.com/test/") }; 
      var data = JsonConvert.SerializeObject(login); 

      var content = new StringContent(data, Encoding.UTF8, "application/json"); 
      var response = await client.PostAsync(@"api/it-IT/auth/token", content); //crash without error, freeze 
      if (response.IsSuccessStatusCode) 
      { 
       var successResult = JsonConvert.DeserializeObject<HttpResponseMessage>(response.Content.ReadAsStringAsync().Result); 
       if (successResult != null) 
       { 
        //return true; 
       } 
       else 
       { 
        //return false; 
       } 
      } 


     } 
     catch (Exception e) 
     { 
      var t = e; 
     } 



    } 
    protected override void RegisterTypes() 
    { 
     Container.RegisterTypeForNavigation<NavigationPage>(); 
     Container.RegisterTypeForNavigation<MainPage>(); 
     Container.RegisterTypeForNavigation<MainPage2>(); 
     Container.RegisterTypeForNavigation<MainPage3>(); 
    } 


} 

Quand le appel postasync ne va pas plus en avant, pas que je reçois aucune erreur, mais ne procède pas.

Mais si j'essaie le même code dans une console d'application, tout fonctionne bien, pourquoi?

class Program 
{ 

     static void Main(string[] args) 
     { 
      Console.WriteLine("A"); 

      CheckLogin().Wait(); 

      Console.WriteLine("K"); 
      Console.ReadKey(); 
     } 


    private static async Task CheckLogin() 
    { 


     try 
     { 
      var login = new Login 
      { 
       Email = "[email protected]", 
       Password = "@test", 
      }; 
      var client = new HttpClient { BaseAddress = new Uri("http://www.api.com/test/") }; 
      var data = JsonConvert.SerializeObject(login); 

      var content = new StringContent(data, Encoding.UTF8, "application/json"); 
      var response = await client.PostAsync(@"api/it-IT/auth/token", content); 
      if (response.IsSuccessStatusCode) 
      { 

      } 


     } 
     catch (Exception e) 
     { 
      var t = e; 
     } 



    } 
} 

Si je tente de faire la même opération dans une commande avec attente je ne travaille pas la même erreur, mais si je ne l'attends, cela fonctionnera très bien, mais App.xaml.cs dans OnInitialized() Je ne peux pas mettre en attente

 public DelegateCommand callCommand { get; set; } 
     public MainPage2ViewModel() 
     { 
      callCommand = new DelegateCommand(Call); 
     } 

     private void Call() 
     { 
      //await CheckLogin(); // work 
      CheckLogin().Wait(); // not work the same problem 
      var i = "pippo"; 
     } 
     private async Task CheckLogin() 
     { 
     .... 
     } 

Y at-il quelque chose à définir avec xamarin ou avec prisme?

Répondre

1

J'ai aussi la même erreur étrange ... i fixer avec cette solution de contournement (utiliser un vide async qui enveloppent tâche async) ...

public App() 
{ 
    InitializeComponent(); 
    Current.MainPage = new LoadingPage(); 
} 

protected override void OnStart() 
{ 
    MagicInit(); 
    base.OnStart(); 
} 

public static async void MagicInit() 
{ 
    var f = await FileSystem.Current.LocalStorage.CreateFileAsync("db.sqlite", CreationCollisionOption.OpenIfExists); 
    DbConnection = f.Path; 
    await DataService.DbFill(); 
    User = await DataService.Instance.Table<SpUser>().FirstOrDefaultAsync(); 
    Current.MainPage = User != null ? (Page)new MainPage() : new LoginPage(); 
}