简体   繁体   English

如何在Xamarin Forms XLabs中使用INetwork?

[英]How can I use INetwork in Xamarin Forms XLabs?

I am having a problem using INetwork from XLabs.Platform. 我在使用XLabs.Platform中的INetwork时遇到问题。 I am getting System.NullReferenceException. 我正在获取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. 但是,由于我是Xamarin的新手,所以我不知道如何设置IOC容器。 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. PS使用XLabs.Platform的文档已过时。 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). 如果要检查是否有Internet连接,建议使用连接插件 (Xamarin组件)。 After adding the Xaamrin Component you can check if an internet connection is avaliable from PCL/Shared project like below 添加Xaamrin组件后,您可以检查PCL / Shared项目是否可以连接Internet,如下所示

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))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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