可访问性返回不准确的状态



我有一个简单的可达性代码,如果我是否可以连接到服务器,它会返回:

-(BOOL)checkConnectionForHost:(NSString*)host{
   _checkStatus = [Reachability reachabilityWithHostname:host];
   NetworkStatus networkStatus = [_checkStatus currentReachabilityStatus];
   return networkStatus != NotReachable;
}

我通过添加类似 google.com 的东西对其进行了测试,它工作正常。但是,如果我输入像 8170319837018 这样的垃圾号码并调用此函数,它仍然返回 TRUE 。但是,如果我向它添加任何字符,例如8170319837018a,它将返回FALSE,因为它应该。我在Reachability上调用了错误的方法吗?我必须检查字符串是 URL 还是 IP 地址?

谢谢!

可达

性存在一些问题。如果您连接到wifi,它将返回它是可回复的,但实际上不会ping主机。更好的方法是使用 NSURLCONNECTION 直接 ping 服务器

+ (BOOL)pingURL:(NSString *)url
{
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1];
    NSURLResponse *response = nil;
    NSError *error = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSLog(@"response %d", [(NSHTTPURLResponse *)response statusCode]);
    if ([(NSHTTPURLResponse *)response statusCode] == 200) {
        return YES;
    }
    return NO;
}
我认为

这是因为内部可达性标志是长数字。因此,当你传递8170319837018时,[_checkStatus currentReachabilityStatus] 必须返回一些不等于 NotReachable(0) 的数字,这就是为什么它必须返回 TRUE。相反,您可以做的是检查每种类型的可达性,如下所示:

-(BOOL)checkConnectionForHost:(NSString*)host{
   _checkStatus = [Reachability reachabilityWithHostname:host];
   NetworkStatus networkStatus = [_checkStatus currentReachabilityStatus];
   return (networkStatus == ReachableViaWiFi) || (networkStatus == ReachableViaWWAN);
}

最新更新