My application uses internet services to fetch and save data. If I try to use these without connectivity I can receive an error. I also want to indicate to the user that there is no connectivity and it is required.
How can I do this effectively?
PS: I use the Template 10 framework.
To handle this pragmatically, you first need to ensure you have upgraded to using Template 10 1.1.12 or higher. With this version you can use the NetworkAvailableService
to test not only internet connectivity but also general network available, too - depending on if your application is an internal app accessing local resources or an external app accessing internet resources.
public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> state)
{
var net = new NetworkAvailableService();
net.AvailabilityChanged = async e =>
{
if (await net.IsNetworkAvailable())
{
// yes network
if (await net.IsInternetAvailable())
{
// yes internet
}
else
{
// no internet
}
}
else
{
// no network
}
};
}
Handling the UI portion of the question is another issue. You can have an IsConnected INPC property in your view-model that causes the visibility of a UI element to change. Or you could use the wonderful NetworkConnectionStateTrigger
to change your visual state. That's how I would do it, by the way. It's the textbook approach, for certain.
Get the State Triggers from https://github.com/dotMorten/WindowsStateTriggers
<VisualStateManager.VisualStateGroups>
<VisualStateGroup>
<VisualState x:Name="connected">
<VisualState.StateTriggers>
<triggers:NetworkConnectionStateTrigger ConnectionState = "Connected" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="MyTextBlock.Text" Value="Internet is available" />
</VisualState.Setters>
</VisualState>
<VisualState x:Name="disconnected">
<VisualState.StateTriggers>
<triggers:NetworkConnectionStateTrigger ConnectionState = "Disconnected" />
</VisualState.StateTriggers>
<VisualState.Setters>
<Setter Target="MyTextBlock.Text" Value="No internet connection"/>
</VisualState.Setters>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
Best of luck!