Search code examples
xamarin.androidxamarin.formsxamarin-studio

Xamarin.Auth PageRenderer redirect to Page in PCL after user authenticated


Hey everyone after opening PageRenderer (Xamarin.Auth) Authentication, Persisting data locally and to the backend I want to close the current Activity and open the registration form or page using information from Fb, Twitter or Gmail. its easy to get this info since it was save locally using SQLite but my problem is closing the current page and opening new Page (Activity) since my Registration page is in PCL (Views) Im using MVVMLight.enter image description here


Solution

  • On Android I used the MessagingCenter to pop out of the Login Page modal that I was using to show the Xamarin Auth login WebView. So it would look like this (note that I show my LoginPage as a modal):

    ContentPage:

    public class LoginPage : ContentPage {
    
        public LoginPage() { }
    
        protected override async void OnAppearing() {
            base.OnAppearing();
    
            MessagingCenter.Unsubscribe<string>(this, "LoginPageDone");
            MessagingCenter.Subscribe<string>(this, "LoginPageDone", async errorMessage => await Navigation.PopModalAsync());
        }
    
        protected override void OnDisappearing() {
            base.OnDisappearing();
            MessagingCenter.Unsubscribe<string>(this, "LoginPageDone");
        }
    }
    

    The in my LoginPage Renderer:

    public class LoginPageRenderer : Xamarin.Forms.Platform.Android.PageRenderer {
    
        protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Xamarin.Forms.Page> e) {
            base.OnElementChanged(e);
    
            if(e.OldElement != null || Element == null) { return; }
    
            LoginPage page = (LoginPage)Element;
    
            Xamarin.Auth.OAuth2Authenticator auth = new Xamarin.Auth.OAuth2Authenticator();
    
            auth.Completed += async (sender, eventArgs) => {
    
                //Do some eventArgs.IsAuthenticated stuff
    
                Xamarin.Forms.MessagingCenter.Send("something", "LoginPageDone"); //Call the event to pop the page
            }
        }
    }
    

    Just for completeness, on iOS, instead of calling the "LoginPageDone" event, I call DismissViewController(true, null); from within auth.Completed.