【问题标题】:How can I use INetwork in Xamarin Forms XLabs?如何在 Xamarin Forms XLabs 中使用 INetwork?
【发布时间】:2016-04-28 23:26:29
【问题描述】:

我在使用 XLabs.Platform 的 INetwork 时遇到问题。我收到 System.NullReferenceException。我不确定问题是否类似于我需要初始化 INetwork 的this。但是,因为我对 Xamarin 非常陌生,所以我不知道如何设置 IOC 容器。我想以一种完全跨平台的方式进行此操作(如果可以避免的话,我想避免放置特定于平台的代码)。谢谢!!

代码:

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 使用 XLabs.Platform 的文档已过期。 (显然)以前正常工作的可达性界面不再起作用。考虑改用this。 This 是一种需要跨平台代码的方法。 Not going to use this 作为作者本人反对这种方法。

【问题讨论】:

    标签: networking xamarin cross-platform xlabs


    【解决方案1】:

    如果您想检查是否有任何 Internet 连接,我建议使用 Connectivity Plugin(Xamarin 组件)。添加 Xaamrin 组件后,您可以检查是否有来自 PCL/共享项目的 Internet 连接,如下所示

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

    【讨论】:

      【解决方案2】:

      你可以通过添加这个属性来填充 ioc:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多