0

간단한 try/catch (PCL 프로젝트에서)를 사용하여 응용 프로그램에 대한 사용자 연결의 유효성을 검사하고 있지만 DisplayAlert() 메서드가 Xamarin 웹 사이트 예제.Xamarin PCL에 오류 메시지를 표시하는 방법

여기 내 using이 있습니다 : 내가 보일 것 또는 내가 메시지를 표시하기 위해 어떻게해야

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 

      } 

:

여기
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; 

코드인가?

+0

'DisplayAlert'는'Xamarin.Forms' 네임 스페이스의'Page' 클래스에있는 public 메소드입니다. 현재 표시된'Page'를 얻은 다음'DisplayAlert'를 호출 할 수 있습니다. – SushiHangover

답변

0

Application.Current.MainPage.DisplayAlert는해야 당신은 작업에서 DisplayAlert을하지 말아야

2

작동합니다. 실패에 대한 호출 클래스로 메시지를 중계하거나 호출 클래스에 대한 예외를 발생시켜야합니다. 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

설정 귀하의 아이폰 OS에서

, 안드로이드, WinRT 및 UWP를 사용하여 토스트 메시지를 표시 할 수 있습니다 프로젝트에 전화하십시오 :

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

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

If Xamarin Forms를 사용하고 있다면, Xamarin.Forms.Init();

권한 당신이 행동을 중단 사용자이기 때문에 먼저 지역 알림을 표시 할 수있는 권한을 요청해야합니다 아이폰 OS에서

. 순서

// 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); 

반환되는 결과는 다음 값 중 하나와 함께 동작하는 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에 메시지를 표시하기 위해 다양한 유형의 경고, 토스트 등이 제공됩니다. 또한 더 나은 UI를 제공합니다.

당신은 다음과 같이 경고를 표시 할 수 있습니다, 설치 한 후 https://www.nuget.org/packages/Acr.UserDialogs/

에서 userdialogs를 설치할 수 있습니다 UserDialogs.Instance.Alert를 ("", "", "OK">);

토스트로 알림을 표시 할 수도 있습니다.