当我开始使用iPhone调试手机以测试我正在制作的应用程序时,它始终不返回任何网络连接,我知道我有一个。设置正确。
我对此很陌生,请保持温柔。
在下面的代码中,
if (defaultNetworkAvailable && ((flags & NetworkReachabilityFlags.IsDirect) != 0))
总是返回false。
{
public class NetworkConnection :INetworkConnection
{
public bool IsConnected { get; set; }
public void CheckNetworkConnection()
{
InternetStatus();
}
public bool InternetStatus()
{
NetworkReachabilityFlags flags;
bool defaultNetworkAvailable = IsNetworkAvailable(out flags);
if (defaultNetworkAvailable && ((flags & NetworkReachabilityFlags.IsDirect) != 0))
{
return false;
}
else if ((flags & NetworkReachabilityFlags.IsWWAN) != 0)
{
return true;
}
else if (flags == 0)
{
return false;
}
return true;
}
private event EventHandler ReachabilityChanged;
private void OnChange(NetworkReachabilityFlags flags)
{
var h = ReachabilityChanged;
if(h != null)
{
h(null, EventArgs.Empty);
}
}
private NetworkReachability defaultReachability;
public bool IsNetworkAvailable(out NetworkReachabilityFlags flags)
{
if(defaultReachability == null)
{
defaultReachability = new NetworkReachability(new System.Net.IPAddress(0));
defaultReachability.SetNotification(OnChange);
defaultReachability.Schedule(CFRunLoop.Current, CFRunLoop.ModeDefault);
}
if(!defaultReachability.TryGetFlags(out flags))
{
return false;
}
return IsReachableWithoutRequiringConnection(flags);
}
private bool IsReachableWithoutRequiringConnection(NetworkReachabilityFlags flags)
{
bool isReachable = (flags & NetworkReachabilityFlags.Reachable) != 0;
bool noConnectionRequired = (flags & NetworkReachabilityFlags.ConnectionRequired) == 0;
if ((flags & NetworkReachabilityFlags.IsWWAN) != 0)
noConnectionRequired = true;
return isReachable && noConnectionRequired;
}
}
}
答案 0 :(得分:0)
要找出为什么if (defaultNetworkAvailable && ((flags & NetworkReachabilityFlags.IsDirect) != 0))
总是返回false的原因。您可以一边打印defaultNetworkAvailable
和flags
来找出问题所在。
运行代码时,我得到:
defaultNetworkAvailable = true;
flags = NetworkReachabilityFlags.Reachable;
因此,它并没有向我返回false。
以下是networkreachabilityflags的文档。
此外,我建议您使用xamarin/essentials/connectivity测试Netconnection
。更简单。
using Xamarin.Essentials;
var current = Connectivity.NetworkAccess;
if (current == NetworkAccess.Internet)
{
// Connection to internet is available
}
document是有关Xamarin.Essentials
的使用方法。
答案 1 :(得分:0)
如果您只是想检查Internet访问,则可以使用简单的帮助程序而无需任何插件。
internal static bool IsInternetAvailable()
{
try
{
Ping myPing = new Ping();
String host = "google.com";
byte[] buffer = new byte[32];
int timeout = 4000;
PingOptions pingOptions = new PingOptions();
PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
return true;
}
catch (Exception)
{
return false;
}
}