Reputation: 9169
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. However, if I type in a junk number like 8170319837018
, and call this function, it still return TRUE
. However, if I add any char to it, like 8170319837018a
, it will return FALSE
, as it should. Am I calling the wrong method on Reachability
? Do I have to check if the string is a URL or an IP address?
Thanks!
Upvotes: 1
Views: 855
Reputation: 818
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. 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);
}
Upvotes: 1
Reputation: 6352
Reachability has some issues. If You are connected to wifi it will return it's rechable but doesn't actually ping the host. Better way would be to use NSURLCONNECTION
to ping the server directly
+ (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;
}
Upvotes: 8