我正在努力获得真实的互联网连接状态。我使用了 Apple 的 Reachability,但它只给了我 wifi 连接的状态,即不包括设备通过 wifi 连接(到路由器或热点)的情况,但 wifi 路由器或热点本身没有连接到互联网。通过从 wifi 路由器拉出互联网输入电缆,可以重现这种情况。可达性的通知器ReachableViaWiFi
同时返回reachabilityForInternetConnection
和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;
}
}
}