Как отобразить сообщение об ошибке в Xamarin PCL

Я делаю простую попытку/поймать (в проекте PCL), чтобы проверить подключение пользователей к приложению, но я не могу найти метод DisplayAlert(), используемый в примере веб-сайтов Xamarin.

Вот мое использование:

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

            }

где я должен искать или что я должен сделать, чтобы отобразить сообщение?


person En_Tech_Siast    schedule 07.05.2017    source источник
comment
DisplayAlert — общедоступный метод класса Page в пространстве имен Xamarin.Forms. Получите текущий отображаемый Page, а затем вы можете вызвать DisplayAlert на нем.   -  person SushiHangover    schedule 07.05.2017


Ответы (4)


Вы не должны делать DisplayAlert из задачи. Вы должны передать вызывающему классу сообщение о сбое или просто создать исключение для вызывающего класса. Для задачи вернуться в пользовательский интерфейс и поднять сообщение — это плохо.

Также вы отключили использование 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");
            }
        }
    }
person Joe Healy    schedule 07.05.2017

Application.Current.MainPage.DisplayAlert должно работать

person Alessandro Caliaro    schedule 07.05.2017

Лучше добавить плагин userdialogs для xamarin. Он предлагает различные типы предупреждений, тостов и т. Д. Для отображения сообщений в пользовательском интерфейсе. Также это дает лучший пользовательский интерфейс.

Вы можете установить пользовательские диалоги с https://www.nuget.org/packages/Acr.UserDialogs/

После установки вы можете показывать оповещения следующим образом: UserDialogs.Instance.Alert("","","OK">);

Вы также можете отображать оповещения в виде тостов.

person Renjith    schedule 08.05.2017

Вы можете отобразить всплывающее сообщение, используя Toasts.Forms.Plugin

Настройка

В проектах iOS, Android, 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);

Возвращаемый результат — это 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
}

Если вы хотите использовать Clicked NotificationAction, вы должны установить IsClickable = true в NotificationOptions.

person Jay Patel    schedule 08.05.2017