Friday, December 19, 2014

Checking For Network Reachabilty In Xamarin

Just ran into this little gem. Everything that I found on how to detect network reachability in says that the following code should be used.
await Network.IsReachable(url, new TimeSpan(NetworkTimeout))
This worked on every iOS device I could get, except the most important device - the client's. It works on iPhone 4s, 5, and 5s, also it worked on my iPad, but not the client's iPhone 5. After much research and frustration, I started diving into the Network.InternetConnectionStatus() function to see if that would be fruitful. I tried the following:
return !Network.InternetConnectionStatus().HasFlag(NetworkStatus.NotReachable);
which naturally (for Xamarin) it is not reliable. I ended up trying the following setup, which seemed to work for on my devices.
var networkstatus = Network.InternetConnectionStatus();
return 
    networkstatus.HasFlag(NetworkStatus.ReachableViaWiFiNetwork) || 
    networkstatus.HasFlag(NetworkStatus.ReachableViaCarrierDataNetwork);
After pushing the build out to the client, he was able to log in. This way has some downsides, as it doesn't check to see if you can actually reach the site you want, but at least you can detect if there is network connectivity.

I would love to submit a bug, but I am not sure how to reliably recreate the issue. It is little things like this that do not build my confidence in Xamarin.

No comments: