如何在iOS中检查网络可达性

时间:2013-09-26 14:05:33

标签: ios objective-c networking reachability

我有一个小问题。我正在使用Reachability类来测试互联网连接,它运行良好。但是假设如果用户正在使用Wifi,但是他们无法访问互联网,则应该重试几秒钟,然后它应该向用户显示警报以切换蜂窝网络。以下是我的代码。当Wifi开启时,我没有指出网络连接速度慢的地方。

self.internetReachable = [Reachability reachabilityForInternetConnection];
[self.internetReachable startNotifier];

//_hasConnectivity = ([self.internetReachable currentReachabilityStatus] != NotReachable);
if([self.internetReachable currentReachabilityStatus] == NotReachable) {
    _hasConnectivity = NO;
}
else if([self.internetReachable currentReachabilityStatus] == ReachableViaWiFi){
    _hasConnectivity = YES;
}
else if([self.internetReachable currentReachabilityStatus] == ReachableViaWWAN) {
    _hasConnectivity = YES;
}

1 个答案:

答案 0 :(得分:6)

尝试使用以下代码返回BOOL值,如果连接可用,则返回YES,否则返回NO

- (BOOL)isNetworkAvailable
{
   CFNetDiagnosticRef dReference;        
   dReference = CFNetDiagnosticCreateWithURL (NULL, (__bridge CFURLRef)[NSURL URLWithString:@"www.apple.com"]);

   CFNetDiagnosticStatus status;
   status = CFNetDiagnosticCopyNetworkStatusPassively (dReference, NULL);        

   CFRelease (dReference);

   if ( status == kCFNetDiagnosticConnectionUp )
   {
      NSLog (@"Connection is Available");
      return YES;
   }
   else 
   {
    NSLog (@"Connection is down");
    return NO;
   }
}