How do i check if user is logged in and user has active internet connection?(PCL project)

After successful login, i just saved email in App.Current.Properties.Add("UEMAIL", uemail.Text);
App.Current.SavePropertiesAsync();

what is the better way to check every time is user logged in and user has active internet connection?

Thanks in advance.

Best Answer

  • RamprasadKRamprasadK USMember ✭✭
    edited October 13 Accepted Answer

    I have added below code in App.cs without using any plugin/nuget package,
    Actually Xamarin Provides Application.Current.Properties to add and savepropertiesasync to save.
    I think it is okay, we can call this PmrUserId any where in the application like App.PmrUserId.

        private static Application AppSettings
        {
            get
            {
                return Application.Current;
            }
        }
        public static string PmrUserId
        {
            get
            {
                if (AppSettings.Properties.ContainsKey("Pmr_user_id"))
                {
                    return AppSettings.Properties["Pmr_user_id"].ToString();
                }
                else
                {
                    return string.Empty;
                }
            }
        }
    

    Similarly for ActiveConnection, I Used Xam.Plugin.Connectivity Nuget.

    `public static bool IsActiveConnection
    {
    get
    {
    if (CrossConnectivity.Current.IsConnected)
    {
    var isreached = CrossConnectivity.Current.IsRemoteReachable("https://www.google.com").Result;
    return isreached;
    }
    else
    {
    return false;
    }

            }
    
        }`
    

    @FabricioBertani

Answers

  • RexHopeRexHope PHMember ✭✭

    For active internet connection, you can make use of
    @JamesMontemagno https://github.com/jamesmontemagno/ConnectivityPlugin

    For checking if user is logged in, it depends on your authentication process. E.g. Did you use token based authentication or different, or did you store user's session somewhere and check if the session has already expired.

  • FabricioBertaniFabricioBertani USMember ✭✭

    You should use Xam.Plugins.Settings to store locally the user email, like this:

    public static class Settings
    {
        private static ISettings AppSettings => CrossSettings.Current;
    
        public static string UEmail
        {
            get => AppSettings.GetValueOrDefault(nameof(UEmail), strings.Empty);
    
            set => AppSettings.AddOrUpdateValue(nameof(UEmail), value);
        }
    }
    

    Then after successful login, before navigating to the next view, save it into settings:

    Settings.UEmail = uemail.Text;

    And finally on App.cs you should override the OnStart method and check if are any email saved into setting, like this:

    protected override void OnStart()
    {
        if(!string.IsNullOrEmpty(Settings.UEmail))
        {
            await Navigation.PushAsync(new YourPageAfterSuccessfulLogin());
        }
    }
    

    And for connectivity you can use the plugin recommended by @RexHope and adding other method to the App.cs like this:

    private async void CheckConnetion()
    {
        if (!CrossConnectivity.Current.IsConnected)
        {
            await DisplayAlert("Alert", "There is no internet connection, please try again later.", "OK");
        }
    }
    

    So your OnStart method would look like this:

    protected override void OnStart()
    {
        CheckConnetion();
    
        if(!string.IsNullOrEmpty(Settings.UEmail))
        {
            await Navigation.PushAsync(new YourPageAfterSuccessfulLogin());
        }
    }
    

    A few cosniderations:
    Above is a sample, take special care with this kind of things.
    I personally wouldn't save user email, instead i would save the user id from the server answer :wink:

  • RamprasadKRamprasadK USMember ✭✭

    @FabricioBertani Thanks for the reply.

    But here i am checking onstart only , what about for other pages.
    It won't go to onstart every time right!

    if you have samples ,please attach here.

  • FabricioBertaniFabricioBertani USMember ✭✭

    @FabricioBertani Thanks for the reply.

    But here i am checking onstart only , what about for other pages.
    It won't go to onstart every time right!

    if you have samples ,please attach here.

    That's why you should do it on the App.cs file, it's related to the entire app.

  • ShahidAli.7296ShahidAli.7296 USMember ✭✭

    I would personally go with "@RexHope" suggestion to monitor the network status, In addition to that I would implement it as a service (if you are using MVVM) thereby registering the service with Dependency injection container and passing an interface of your service into each of your viewmodel to be stored as property & consume it whenever u feel the need for it.

    The question of whether a user is logged in or not is a bit of vague and broad question in my opinion, however I would either go with what "@FabricioBertani" suggested or use another plugin called "Akavache". Depending on how you do your authentication, i.e. using OAuth or your own API to check the credentials against your local database, once the user get authenticated, that API call should return something called "Token" and you store that token either using "Xam.Plugins.Settings" or "Akavache" on your client device. The next time your app comes into the foreground (i.e. become active app on the screen), you check for those settings whether they have been populated previously using a "key", if so then the user was authenticated previously otherwise present them with the login screen.

  • RamprasadKRamprasadK USMember ✭✭

    @FabricioBertani Yeah, Actually i am new to xamarin and didn't know much about xamarin.
    If you have any sample code ,please attach here.

  • RamprasadKRamprasadK USMember ✭✭
    edited October 13 Accepted Answer

    I have added below code in App.cs without using any plugin/nuget package,
    Actually Xamarin Provides Application.Current.Properties to add and savepropertiesasync to save.
    I think it is okay, we can call this PmrUserId any where in the application like App.PmrUserId.

        private static Application AppSettings
        {
            get
            {
                return Application.Current;
            }
        }
        public static string PmrUserId
        {
            get
            {
                if (AppSettings.Properties.ContainsKey("Pmr_user_id"))
                {
                    return AppSettings.Properties["Pmr_user_id"].ToString();
                }
                else
                {
                    return string.Empty;
                }
            }
        }
    

    Similarly for ActiveConnection, I Used Xam.Plugin.Connectivity Nuget.

    `public static bool IsActiveConnection
    {
    get
    {
    if (CrossConnectivity.Current.IsConnected)
    {
    var isreached = CrossConnectivity.Current.IsRemoteReachable("https://www.google.com").Result;
    return isreached;
    }
    else
    {
    return false;
    }

            }
    
        }`
    

    @FabricioBertani

Sign In or Register to comment.