ios - Xamarin 表单检查 iOS 上的 wifi 连接
问题描述
我正在开发一个以编程方式连接到热点的应用程序。我需要检查连接是否完全建立,为此我使用 Xamarin.Essentials.Connectivity 包和以下方法:
public bool IsWifiConnected()
{
IEnumerable<ConnectionProfile> profiles = Connectivity.ConnectionProfiles;
return profiles.Contains(ConnectionProfile.WiFi);
}
不幸的是,该方法从连接开始建立并且尚未完全准备好(仍在握手)的那一刻起返回 true。有没有办法检查连接是否完全准备好?
解决方案
解决方案:
如果您想在 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");
}
推荐阅读
- python - 为温度转换设置 if 语句?
- tensorflow - 将 tensorflow 模型从本地机器转换到 AWS SageMaker 时读取 S3 存储桶时出现问题
- groovy - Groovy 获取 xml 标签属性值
- javascript - 制作非常简单的应用程序,包括前端和后端技能(js、node.js、psql、react...)
- python - 从()中提取特定信息的最简单方法是什么?
- android - 如何打开 Native Android App 中的数据并将其传递给 Flutter Android App?
- android - Android 应用:用户通过 Intent.ACTION_GET_CONTENT 选择 CSV 文件。然后如何将此 CSV 文件导入到 sqlite 数据库表中?
- reactjs - 有没有办法使用 axios 将图像上传到 Firebase 并从中加载?
- python - 如何在 Python 中根据需要编写文件段落?
- python - 在没有 Jupyter Notebook 的情况下使用 Kepler GL