When developing mobile applications, handling the internet connection changes it’s a must thing to do. In most popular apps, when there’s no connection a message is shown to give awareness to the user about why they won’t see any new content.
In this article, I will show you how to do just that in Xamarin Forms by providing a few alternatives to show the no connection message.
Let’s start
First, let’s handle all the connection changes logic, which can be done by using the Xamarin.Essentials librar.
1-Install Xamarin.Essentials
2- On your Android project
2.1 Initialize Xamarin Essentials
2.2 Add the ACCESS_NETWORK_STATE permission in your Android Manifest
3- Create a BaseViewModel class from which all your ViewModels will inherit
This base ViewModel
PDT: As you can see I’m implementing INotifyPropertyChanged, that’s because I’m using this library to handle the PropertyChanged events.
4-Change all your ViewModels to inherit from BaseViewModel
Now that we have the internet connection handling logic, we just need to worry about alerting the user that connection state has changed. Will show you a few alternatives to do this:
1-Showing an Alert UI
Create a new custom view, which will bind it’s IsVisible property to the IsNotConnected property created in the ViewModel, so that we can show/hide it according to if there’s internet or not.
After that, add this new view to all your pages.
2-Showing an Alert UI with an animation
This uses the same concept shown above, the only difference is that we are going to add an animation. For that, we are going to use Lottie.
If you want to know how to add the Lottie animations to your project you can check this article.
There are a lot of animations you can use, check here.
3-Showing a Toast
If you don’t want to add a view to all your pages, you can display a simple Toast. To achieve this there are some plugins you could use like Acr.UserDialog plugin.
4-Showing a local notification Alert
For the next approach, will use Toast
Other ideas:
- Display an alert showing a no internet connection message
- Show an alert PopUp with a connection message/animation (Could be by using the Rg.Plugin.PopUps Plugin)
- Create an empty view concept and replace your page content when there is no internet connection. So that the user won’t be able to use the application while the connection is down.
That’s all for now. You can check the full source code here.
If you have any other suggestions on ways to do it, don’t forget to leave a comment below.
Happy coding! 🙂
1 Comment
Great article!
One thing to point out is that using a deconstructor is not very performant. It might be better to trigger OnAppearing and OnDisappearing events from a BaseContentPage into your BaseViewModel.