0

我正在做一個簡單的try/catch(在PCL項目中)來驗證用戶與應用程序的連接,但我似乎找不到DisplayAlert()方法用於Xamarin網站的例子。如何在Xamarin中顯示錯誤消息PCL

這裏是我的usings:

using Newtonsoft.Json; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net.Http; 
using System.Net.Http.Headers; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Input; 
using System.Security; 
using System.Diagnostics; 

下面是代碼:

public async Task Connexion() 
     { 
      // on met en place un try catch pour déceler toute erreur dans la procédure de connexion 
      try 
      { 
       // url de récupération du json de l'acteur 
       string urlActeur = "http://10.0.0.5/ppe3JoJuAd/gsbAppliFraisV2/webservices/w_visiteur.php" + "?" + "login=" + Login + "&" + "pass=" + Pass; 

       //instanciation du client http qui envoi un header json 
       HttpClient clientActeur = new HttpClient(); 
       clientActeur.DefaultRequestHeaders.Accept.Clear(); 
       clientActeur.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

       //réponse à la requête Http 
       var response = await clientActeur.GetAsync(urlActeur); 
       var json = response.Content.ReadAsStringAsync().Result; 
       var acteurJson = JsonConvert.DeserializeObject<ActeurJson>(json); 

       //on vérifie les informations de connexion du user (ici cela se ait avec oldMdp car pas d'implémentation du SHA1 actuellement en Xamarin, auquel cas nous auions converti le contenu du champ pass en sha1 puis vérification avec le champ mdp de l'acteur) 
       if (acteurJson.Acteur.login == login && acteurJson.Acteur.mdp == acteurJson.Acteur.oldMdp) 

        App.Current.MainPage = new VisitePage(); 
      } 
      catch 
      { 
       await DisplayAlert()//intelisense does not find the using or the required dll 

      } 

,我應該看或我應該怎麼做,以顯示消息?

+0

'DisplayAlert'是'Xamarin.Forms'命名空間中'Page'類中的公共方法。獲取當前顯示的「頁面」,然後您可以調用它上面的「DisplayAlert」。 – SushiHangover

回答

0

Application.Current.MainPage.DisplayAlert應該工作

2

你不應該從一個任務做了DisplayAlert。你應該把一個消息轉發給調用類,告訴失敗,或者只是將異常提交給調用類。對於返回到UI並提出消息的任務是不好的。

此外,您對HttpClient的使用已關閉。 HttpClient旨在用作單例方法。嘗試併爲每個項目或模塊創建一個靜態單例。

之所以這麼說,試試這個:

public class ConnexionHelper 
{ 
    public async Task Connexion() 
    { 
     try 
     { 
      System.Diagnostics.Debug.WriteLine("trying stuff"); 
     } 
     catch(Exception ex) 
     { 
      Xamarin.Forms.Page ourPage = App.Current.MainPage.Navigation.NavigationStack.LastOrDefault(); 
      if (ourPage != null) 
      { 
       await ourPage.DisplayAlert("eeek", "error has occurrred", "not ok"); 
      } 
     } 
    } 
0

可以使用Toasts.Forms.Plugin

設置

在iOS,安卓,WinRT中和UWP顯示敬酒消息項目請致電:

DependencyService.Register<ToastNotification>(); // Register your dependency 
ToastNotification.Init(); 

// If you are using Android you must pass through the activity 
ToastNotification.Init(this); 

如果你正在使用Xamarin Forms,你必須在調用Xamarin.Forms.Init()之後執行此操作。

權限

在iOS中,你必須申請許可首先顯示本地通知,因爲它是中斷操作的用戶。

// Request Permissions 
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0)) 
{ 
    // Request Permissions 
    UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (granted, error) => 
    { 
     // Do something if needed 
    }); 
} 
else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0)) 
{ 
    var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes(
    UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null); 

    app.RegisterUserNotificationSettings(notificationSettings); 
} 

使用

爲了使用相關的服務來解決IToastNotificator。

var notificator = DependencyService.Get<IToastNotificator>(); 

var options = new NotificationOptions() 
      { 
       Title = "Title", 
       Description = "Description" 
      }; 

var result = await notificator.Notify(options); 

返回的結果是帶有Action的NotificationResult,其中包含以下值之一。

[Flags] 
public enum NotificationAction 
{ 
    Timeout = 1, // Hides by itself 
    Clicked = 2, // User clicked on notification 
    Dismissed = 4, // User manually dismissed notification 
    ApplicationHidden = 8, // Application went to background 
    Failed = 16 // When failed to display the toast 
} 

如果您想要點擊NotificationAction,您必須在NotificationOptions中設置IsClickable = true。

1

它更好地爲xamarin添加userdialogs插件。它提供了不同類型的警報,吐司等在UI中顯示消息。它也提供了更好的用戶界面。

您可以從https://www.nuget.org/packages/Acr.UserDialogs/

安裝userdialogs安裝後,可以自動顯示警告如下: UserDialogs.Instance.Alert( 「」, 「」, 「OK」>);

您還可以顯示警報作爲吐司。