简体   繁体   English

可达性返回错误状态

[英]Reachability returning inaccurate status

I have a simple Reachability code that returns if I can connect to a server or not: 我有一个简单的可达性代码,如果我可以连接到服务器,则返回该代码:

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

I tested it by adding stuff like google.com , and it works fine. 我通过添加google.com东西对其进行了测试,并且效果很好。 However, if I type in a junk number like 8170319837018 , and call this function, it still return TRUE . 但是,如果我输入一个像8170319837018这样的垃圾数字,并调用此函数,它仍然会返回TRUE However, if I add any char to it, like 8170319837018a , it will return FALSE , as it should. 但是,如果我向其中添加任何字符,例如8170319837018a ,它将按应返回FALSE Am I calling the wrong method on Reachability ? 我是否对Reachability调用了错误的方法? Do I have to check if the string is a URL or an IP address? 我是否需要检查字符串是URL还是IP地址?

Thanks! 谢谢!

Reachability has some issues. 可达性有一些问题。 If You are connected to wifi it will return it's rechable but doesn't actually ping the host. 如果您已连接到wifi,它将返回它的位置,但实际上并未对主机进行ping操作。 Better way would be to use NSURLCONNECTION to ping the server directly 更好的方法是使用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;
}

I think this is because the internal reachability flags are long numbers. 我认为这是因为内部可达性标记是长数字。 So when you pass 8170319837018 the [_checkStatus currentReachabilityStatus] must be returning some number which is not equal to NotReachable(0) and that's why it must be returning TRUE. 因此,当您传递8170319837018时,[_ checkStatus currentReachabilityStatus]必须返回一个不等于NotReachable(0)的数字,这就是为什么它必须返回TRUE的原因。 What you can instead do is to check against each type of reachability like below: 您可以做的是对照每种可及性类型进行检查,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM