Introduction
This article explains how to check network connectivity in iOS and Android.
I had to do the same in one of my project using Xamarin forms, but I could not find any sample that does the same. There are samples in Xamarin that do the same natively. But I wanted to achive the same using forms.
I have taken code from each platform and used dependency services to check connectivty in the Xamarin forms pages. Please find the attached for sample code.
Background
Mobile development using Xamarin forms.
Using the code
In the portable class library add a class file called INetworkConnection as shown below:
public interface INetworkConnection
{
bool IsConnected { get; }
void CheckNetworkConnection();
}
and go the Android project and add code as show below, here adding assembly is important and its class name in it.
[assembly: Dependency(typeof(NetworkConnection))]
namespace FormsNetworkConnectivity.Droid
{
public class NetworkConnection : INetworkConnection
{
public bool IsConnected { get; set; }
public void CheckNetworkConnection()
{
var connectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService);
var activeNetworkInfo = connectivityManager.ActiveNetworkInfo;
if (activeNetworkInfo != null && activeNetworkInfo.IsConnectedOrConnecting)
{
IsConnected = true;
}
else
{
IsConnected = false;
}
}
}
}
and on iOS project add below code and remember its assebly attribute
[assembly: Dependency(typeof(NetworkConnection))]
namespace FormsNetworkConnectivity.iOS.Network
{
public class NetworkConnection : INetworkConnection
{
public bool IsConnected { get; set; }
public void CheckNetworkConnection()
{
InternetConnectionStatus();
}
private void UpdateNetworkStatus()
{
if (InternetConnectionStatus())
{
IsConnected = true;
}
else if (LocalWifiConnectionStatus())
{
IsConnected = true;
}
else
{
IsConnected = false;
}
}
private event EventHandler ReachabilityChanged;
private void OnChange(NetworkReachabilityFlags flags)
{
var h = ReachabilityChanged;
if (h != null)
h(null, EventArgs.Empty);
}
private NetworkReachability defaultRouteReachability;
private bool IsNetworkAvailable(out NetworkReachabilityFlags flags)
{
if (defaultRouteReachability == null)
{
defaultRouteReachability = new NetworkReachability(new IPAddress(0));
defaultRouteReachability.SetCallback(OnChange);
defaultRouteReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
}
if (!defaultRouteReachability.TryGetFlags(out flags))
return false;
return IsReachableWithoutRequiringConnection(flags);
}
private NetworkReachability adHocWiFiNetworkReachability;
private bool IsAdHocWiFiNetworkAvailable(out NetworkReachabilityFlags flags)
{
if (adHocWiFiNetworkReachability == null)
{
adHocWiFiNetworkReachability = new NetworkReachability(new IPAddress(new byte[] { 169, 254, 0, 0 }));
adHocWiFiNetworkReachability.SetCallback(OnChange);
adHocWiFiNetworkReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
}
if (!adHocWiFiNetworkReachability.TryGetFlags(out flags))
return false;
return IsReachableWithoutRequiringConnection(flags);
}
public static bool IsReachableWithoutRequiringConnection(NetworkReachabilityFlags flags)
{
bool isReachable = (flags & NetworkReachabilityFlags.Reachable) != 0;
bool noConnectionRequired = (flags & NetworkReachabilityFlags.ConnectionRequired) == 0;
if ((flags & NetworkReachabilityFlags.IsWWAN) != 0)
noConnectionRequired = true;
return isReachable && noConnectionRequired;
}
private bool InternetConnectionStatus()
{
NetworkReachabilityFlags flags;
bool defaultNetworkAvailable = IsNetworkAvailable(out flags);
if (defaultNetworkAvailable && ((flags & NetworkReachabilityFlags.IsDirect) != 0))
{
return false;
}
else if ((flags & NetworkReachabilityFlags.IsWWAN) != 0)
{
return true;
}
else if (flags == 0)
{
return false;
}
return true;
}
private bool LocalWifiConnectionStatus()
{
NetworkReachabilityFlags flags;
if (IsAdHocWiFiNetworkAvailable(out flags))
{
if ((flags & NetworkReachabilityFlags.IsDirect) != 0)
return true;
}
return false;
}
}
}
Now go the page you want to check connectivity and do similar as below
var networkConnection = DependencyService.Get<INetworkConnection>();
networkConnection.CheckNetworkConnection();
var networkStatus = networkConnection.IsConnected ? "Connected" : "Not Connected";
var speak = new Button
{
Text = "Click to check Network connectivity",
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand,
};
speak.Clicked += (sender, e) =>
{
speak.Text = DependencyService.Get<INetworkConnection>().IsConnected ? "You are Connected" : "You are Not Connected";
};
Content = speak;
Thats you need to do to get Network connectivity using Xamarin forms from iOS and Android
I am a, hands-on, Microsoft C# Analyst Programmer using Xamarin, Azure, WPF and MVC as my preferred tools, also as Team Lead and Scrum Master. My experience include in analysis, object oriented design, development and implementation of client, server, web and windows based applications and enterprise mobile apps using latest Microsoft technologies such as MVC, WPF and Xamarin Forms.
I have worked with Microsoft technologies for over 10 years building software for various private sector companies, applying both technical knowledge and managerial expertise.
My preferred technology stack includes C#, Azure, WPF, MVC, Entity Framework, Xamarin and SQL Server and highly prefer working on various design patterns and architectures.
An integral part of my work is to provide my clients with a high standard of understandable technical documentation: I have written few articles listed few page down in this resume, designs, as well as User Guides.
Using Azure for over 1.5 year, migrating application to the cloud, fully managed continuous integration for all environments.