2016-10-07 13 views
0

Я создаю приложение, используя Xamarin.Forms и Xamarin.Auth для входа в Facebook.Xamarin.Forms PopModalAsync не работает

Вот что я делаю:

App.cs:

public App() 
{ 
    if (IsAuthenticated) 
    { 
     MainPage = new NavigationPage(new DetailPage()); 
    } 
    else { 
     MainPage = new NavigationPage(new WelcomePage()); 
    } 
} 

public Action SuccessfulLoginAction 
{ 
    get 
    { 
     return new Action(() => MainPage.Navigation.PopModalAsync()); 
    } 
} 

WelcomePage:

using System; 
using System.Threading.Tasks; 
using Xamarin.Forms; 

namespace Project 
{ 
    public class WelcomePage : ContentPage 
    { 
     public WelcomePage() 
     { 
      var login = new Button { Text = "Login" }; 
      login.Clicked += async (sender, e) => 
      { 
       await Navigation.PushModalAsync(new LoginPage()); 
      }; 

      Content = new StackLayout 
      { 
       BackgroundColor = Color.FromHex("F0C640"), 
       Padding = new Thickness(10, 40, 10, 10), 
       Children = { 
        new Label { Text = "Welcome", FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)), HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.White }, 
        new Label { Text = "Please login", FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)), HorizontalTextAlignment = TextAlignment.Center, TextColor = Color.White }, 
        login 
       } 
      }; 
     } 
    } 
} 

LoginPage:

using Xamarin.Forms; 
using System.Threading.Tasks; 

namespace Project 
{ 
    public class LoginPage : ContentPage 
    { 
    } 
} 

LoginRenderer:

using System; 
using Xamarin.Auth; 
using Xamarin.Forms.Platform.iOS; 
using Xamarin.Forms; 
using Project; 
using Project.iOS; 

[assembly: ExportRenderer(typeof(LoginPage), typeof(LoginPageRenderer))] 

namespace Project.iOS 
{ 
    public class LoginPageRenderer : PageRenderer 
    { 
     bool IsShown; 

     public override void ViewDidAppear(bool animated) 
     { 
      base.ViewDidAppear(animated); 

      // Fixed the issue that on iOS 8, the modal wouldn't be popped. 
      // url : http://stackoverflow.com/questions/24105390/how-to-login-to-facebook-in-xamarin-forms 
      if (!IsShown) 
      { 
       IsShown = true; 

       var auth = new OAuth2Authenticator(
        clientId: App.Instance.OAuthSettings.ClientId, // your OAuth2 client id 
        scope: App.Instance.OAuthSettings.Scope, // The scopes for the particular API you're accessing. The format for this will vary by API. 
        authorizeUrl: new Uri(App.Instance.OAuthSettings.AuthorizeUrl), // the auth URL for the service 
        redirectUrl: new Uri(App.Instance.OAuthSettings.RedirectUrl)); // the redirect URL for the service 

       auth.Completed += (sender, eventArgs) => 
       { 
        // We presented the UI, so it's up to us to dimiss it on iOS. 
        DismissViewController (true, null); 

        if (eventArgs.IsAuthenticated) 
        { 
         Console.WriteLine("Authenticated!!!!"); 
         App.Instance.SaveToken(eventArgs.Account.Properties["access_token"]); 
         App.Instance.SuccessfulLoginAction.Invoke(); 
        } 
        else { 
         Console.WriteLine("Not authenticated!!!!"); 
         App.Instance.CanceledLoginAction.Invoke(); 
        } 
       }; 
       PresentViewController(auth.GetUI(), true, null); 
      } 

     } 
    } 
} 

Все работает очень хорошо, я могу отображать страницу Modal с содержанием Facebook и логином. Когда аутентификация завершена, она проходит через событие auth.Completed и вызывает приложение App.Instance.SuccessfulLoginAction.Invoke(); но MainPage.Navigation.PopModalAsync() (в App.cs) не закрывает страницу Modal.

Что я угадываю, так это модальная страница открыта на странице приветствия, и я пытаюсь ее закрыть в файле App.cs. Возможно ли, что это не относится к одному и тому же объекту, поэтому я не могу закрыть его здесь? Как вы, ребята, делаете, чтобы закрыть свою модальную страницу при создании конкретного рендеринга на платформе?

Как сделать, чтобы закрыть эту страницу мода?

Благодаря

ответ

0

Хотя не совсем шикарно, вот как я обращался аутентификации в моем образце для проверки подлинности:

public void HandleLoginSucceeded(object sender, EventArgs e) 
    { 
     MainPage = new WelcomePage(); 
    } 

Поскольку App.cs является точкой входа, я просто сбросить MainPage, чтобы указать на новый место нахождения. Я не знаю, какие компромиссы это может вызвать; однако я знаю, что он работает. Вы можете увидеть мой образец на Github, чтобы увидеть мою реализацию.

 Смежные вопросы

  • Нет связанных вопросов^_^