我正在努力获取真实的互联网连接状态。我使用过 Apple 的 Reachability,但它只提供 wifi 连接的状态,即不涵盖设备通过 wifi 连接(连接到路由器或热点)但 wifi 路由器或热点本身未连接到互联网时的情况。通过从 WiFi 路由器拔出互联网输入电缆,可以重现这种情况。可达性的通知程序返回ReachableViaWiFi
对彼此而言reachabilityForInternetConnection
and ReachabilityWithHostName
。我正在解决这个问题。我尝试通过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;
}
}
}
根据可达性 https://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007324-Intro-DontLinkElementID_2它不仅检查 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;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)