step-up-labs / firebase-authentication-dotnet

C# library for Firebase Authentication
MIT License
376 stars 129 forks source link

[Help wanted] Best approach for login & main window navigation in Xamarin forms #190

Open PunditSharp opened 1 year ago

PunditSharp commented 1 year ago

This isn't a question about this library as such, but more a question around its usage...I'm trying to figure out the best way to handle navigation between my login page and the (single) main page of my app, and I can't quite get my head around it. It's working on Android, but is failing on iOS with an "Application windows are expected to have a root view controller at the end of application launch" error. I suspect it is something to do with the fact that I am instantiating the main window on successful auth inside the AuthStateChanged method of the App class. I had a similar issue on Android, which I fixed by wrapping the instantiation in Device.InvokeOnMainThread. I have a feeling that I'm not handling the navigation model in the right way, but as a n00b at this, I'm not sure how best to proceed. App class code is as follows:

public partial class App : Application
    {
        public static FirebaseAuthClient AuthClient;
        FirebaseAuthConfig config = new FirebaseAuthConfig
        {
            ApiKey = "AIzaSyDdXOgqwLro1FDbp12OUeCdCj6SfNUYdDo",
            AuthDomain = "treetrackfirebase.firebaseapp.com",
            Providers = new FirebaseAuthProvider[]
           {
                new EmailProvider()
           },
           UserRepository = new XamarinPropertiesRepository()
        };

        public App()
        {
            InitializeComponent();

            AuthClient = new FirebaseAuthClient(config);
            if (AuthClient.User != null ) 
            {

            }
        }

        private async void AuthStateChanged(object sender, UserEventArgs e)
        {

            if (e.User!= null ) 
            {
                try
                {
                    string idToken = await e.User.GetIdTokenAsync();
                }
                catch (FirebaseAuthHttpException)
                {
                    AuthClient.SignOut();
                    MainPage = new LoginPage();
                    return;
                }

                Device.BeginInvokeOnMainThread(() =>
                {
                    MainPage = new MainPage();
                });
            }
            else
            {
                MainPage = new LoginPage();
            }
        }

        protected override void OnStart()
        {
            AuthClient.AuthStateChanged += AuthStateChanged;
        }

        protected override void OnSleep()
        {
        }

        protected override void OnResume()
        {
        }
    }

Any suggestions / guidance welcomed!