Jonathan
Jonathan

Reputation: 696

C#: How to check internet access in PCL project

I'm trying to check for an internet connection in a PCL project that is used by a Xamarin.iOS and Xamarin.Android projects. I'm gathering from my research that WebClient can't be used in a PCL, but I haven't been able to find a satisfactory solution that doesn't use WebClient. Here's the code I'd like to use:

try
{
    using (var client = new WebClient())
    {
        using (var stream = client.OpenRead("http://www.google.com"))
        {
            return true;
        }
    }
}
catch
{
    return false;
}

Does anyone know of a good solution that is similarly simple?

Upvotes: 0

Views: 679

Answers (1)

JimBobBennett
JimBobBennett

Reputation: 2159

The easiest way is to use the Connectivity plugin from James Montemagno:

https://github.com/jamesmontemagno/ConnectivityPlugin

You install this, then call:

CrossConnectivity.Current.IsConnected

from your PCL. You can even subscribe to an event to see when connectivity changes:

CrossConnectivity.Current.ConnectivityChanged += <handler>

This works on iOS and Android.

Upvotes: 2

Related Questions