首页 > 解决方案 > Xamarin 表单检查 iOS 上的 wifi 连接

问题描述

我正在开发一个以编程方式连接到热点的应用程序。我需要检查连接是否完全建立,为此我使用 Xamarin.Essentials.Connectivity 包和以下方法:

public bool IsWifiConnected()
{
    IEnumerable<ConnectionProfile> profiles = Connectivity.ConnectionProfiles;
    return profiles.Contains(ConnectionProfile.WiFi);
}

不幸的是,该方法从连接开始建立并且尚未完全准备好(仍在握手)的那一刻起返回 true。有没有办法检查连接是否完全准备好?

标签: iosxamarinwificonnectivity

解决方案


解决方案: 如果您想在 WIFI 网络没有 Internet 连接时在 Forms 中检查 Internet 可用性。您可以使用DependencyService它来实现它。参考以下代码。

在 Forms 中,创建一个界面

using System;
namespace xxx
{
  public interface INetworkAvailable
  {

    bool IsNetworkAvailable();
  }
}

在 iOS 项目中

using System;
using Xamarin.Forms;
using Foundation;

[assembly: Dependency(typeof(IsNetworkAvailableImplement))]
namespace xxx.iOS
{
  public class IsNetworkAvailableImplement:INetworkAvailable
  {
    public IsNetworkAvailableImplement()
    {
    }

    bool INetworkAvailable.IsNetworkAvailable()
    {
        NSString urlString = new NSString("https://captive.apple.com");

        NSUrl url = new NSUrl(urlString);

        NSUrlRequest request = new NSUrlRequest(url, NSUrlRequestCachePolicy.ReloadIgnoringCacheData, 3);

        NSData data = NSUrlConnection.SendSynchronousRequest(request, out NSUrlResponse response, out NSError error);

        NSString result = NSString.FromData(data,NSStringEncoding.UTF8);

        if(result.Contains(new NSString("Success")))
        {
            return true;
        }

        else
        {
            return false;
        }

    }
  }
}

现在你可以在表单中调用它,就像

bool isAvailable= DependencyService.Get<INetworkAvailable>().IsNetworkAvailable();

if(isAvailable)
{
  Console.WriteLine("network is available");
}

else
{
  Console.WriteLine("network is unavailable");
} 

推荐阅读