Best way to check for internet connection in cross-platform Xamarin projects

I’m working on a multi-platform project built on Xamarin and C#. We retrieve a lot of data from the internet, and we check for an internet connection before we do so we can notify the user if we had problems getting the data they’re looking for. However, the way we checked for the connection across the different projects wasn’t consistent and kind of depended on which developer needed the functionality and where he needed it.

This project has been in the works for quite some time now, and I was recently tasked with abstracting as much logic as possibly out of the various platform-specific projects and into one common logic layer, and this connection checking logic I mentioned was one of the first things I found to refactor. I created a new class in the common project and began implementing it, but I ran into a road block.

The method we were using previously required the WebClient class in the System.Net namespace, but that class is apparently not accessible from PCL projects (which is what my common layer is).

Hrm.

I googled for several hours and read way to many stackoverflow threads over and over, vainly trying to find an answer. Finally, I asked my own stackoverflow question. My tendency is to shy away from asking questions there because I feel like I won’t get a response for weeks, and when one does come in it’ll be no good, but this time I got an answer in less than 5 minutes.

And it was a good answer too. It turns out that someone else already encountered the problem I was having, and had build a NuGet package to fix it. I installed the plugin, and while I had to make a few changes to get everything working (I removed this whole module from the shared logic layer and implemented the plugin directly in each of the platform-specific projects), after a few short minutes of work with the no-nonsense properties exposed by the plugin I’ve removed all of my tedious custom implementation, and the codebase is that much more streamlined.

Hopefully this post can help someone else before they spend 4.5 hours digging for a solution like I did :). Let me know if you have any questions, thoughts, or if the plugin solved your problem in the comments!