gpt4 book ai didi

iphone - 当 wifi 源失去连接时如何检测互联网可达性丢失?

转载 作者:可可西里 更新时间:2023-11-01 03:08:16 24 4
gpt4 key购买 nike

我正在努力获取真实的互联网连接状态。我使用了 Apple 的 Reachability,但它只给我 wifi 连接的状态,即不包括设备通过 wifi 连接(到路由器或热点)但 wifi 路由器或热点本身未连接到互联网的情况。通过从 wifi 路由器拉互联网输入电缆可以重现这种情况。可达性通知程序为 reachabilityForInternetConnectionReachabilityWithHostName 返回 ReachableViaWiFi。我非常想解决这个问题。我也通过 NSURLConnection 尝试过,但这太耗电了,而且我个人不喜欢这种持续发出 URL 请求的解决方案,尽管是在后台线程中。

这是我正在使用的代码(由 SO 人员提供,但不记得确切的链接)

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];

internetReachable = [[Reachability reachabilityForInternetConnection] retain];
[internetReachable startNotifier];

// check if a pathway to a random host exists
hostReachable = [[Reachability reachabilityWithHostName: @"www.google.com"] retain];
[hostReachable startNotifier];

然后在观察者方法中:

 - (void) checkNetworkStatus:(NSNotification *)notice{

// called after network status changes

NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)

{
case NotReachable:
{
NSLog(@"The internet is down.");
self.isInternetReachable = NO;

break;

}
case ReachableViaWiFi:
{
NSLog(@"The internet is working via WIFI.");
self.isInternetReachable = YES;

break;

}
case ReachableViaWWAN:
{
NSLog(@"The internet is working via WWAN.");
self.isInternetReachable = YES;

break;

}
}
NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
switch (hostStatus)

{
case NotReachable:
{
NSLog(@"A gateway to the host server is down.");
self.isHostReachable = NO;

break;

}
case ReachableViaWiFi:
{
NSLog(@"A gateway to the host server is working via WIFI.");
self.isHostReachable = YES;

break;

}
case ReachableViaWWAN:
{
NSLog(@"A gateway to the host server is working via WWAN.");
self.isHostReachable = YES;

break;

}
}
}

最佳答案

根据 Reachability它不仅检查 wifi,还检查 WWAN/3G 和无互联网访问权限,您认为为什么它不检查 WIFI 以外的内容?

 typedef enum {

NotReachable = 0,

ReachableViaWiFi,

ReachableViaWWAN

} NetworkStatus;

如果你想检查特定主机的可达性,那么你可以像这样自己设置主机

Reachability *hostReach = [Reachability reachabilityWithHostName: @"www.google.com"];

NetworkStatus netStatus = [hostReach currentReachabilityStatus];

switch (netStatus)
{
case ReachableViaWWAN:
{
NSLog(@"WWAN/3G");
break;
}
case ReachableViaWiFi:
{
NSLog(@"WIFI");
break;
}
case NotReachable:
{
NSLog(@"NO Internet");
break;
}
}

关于iphone - 当 wifi 源失去连接时如何检测互联网可达性丢失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15146607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com