简体   繁体   中英

How can I use INetwork in Xamarin Forms XLabs?

I am having a problem using INetwork from XLabs.Platform. I am getting System.NullReferenceException. I am not sure if the problem is similar to this where I need to initialize INetwork. However, because I am very new to Xamarin I have no idea how to set up the IOC container. I'd like to this in a completely cross-platform way (I'd like to avoid putting platform specific code if I can avoid it). Thanks!!

Code:

using XLabs.Ioc;
using XLabs.Platform;
...
namespace XXX
{
   class XXX
    {
    public static bool isOnline()
    {

        var networkservice = DependencyService.Get<XLabs.Platform.Services.INetwork>();
        var status = networkservice.InternetConnectionStatus();
        return (
            (status.Equals(XLabs.Platform.Services.NetworkStatus.ReachableViaCarrierDataNetwork))
            || (status.Equals(XLabs.Platform.Services.NetworkStatus.ReachableViaWiFiNetwork))
            || (status.Equals(XLabs.Platform.Services.NetworkStatus.ReachableViaUnknownNetwork)));
    }

}

}

PS The documentation for using XLabs.Platform is out of date. The (apparently) previously functioning Reachability interface doesn't work anymore. Thinking about using this instead. This is an approach that requires cross platform code. Not going to use this as the author himself disses the approach.

If you want to check if there is any Internet Connection, I would suggest to use Connectivity Plugin (Xamarin Component). After adding the Xaamrin Component you can check if an internet connection is avaliable from PCL/Shared project like below

if (CrossConnectivity.Current.IsConnected)
{ // Make API call here 
} 
else 
      DisplayAlert("Connectivity Issue", "Please Connect to a Network", "OK") ;

通过添加以下属性来填充ioc:

[assembly: Xamarin.Forms.Dependency(typeof(NameOfClassImplementingAnInterface))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM