Search code examples
iosreachabilityinternet-connection

iOS - Connection checker with Reachability class is failed. (reachabilityWithHostName:)


I wrote a connection checker using Apple's Reachability class' reachabilityWithHostName: method. Here is my code.

-(BOOL)checkConnection{
Reachability *reachability = [Reachability reachabilityWithHostName:@"www.example.com"];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if (remoteHostStatus != NotReachable) {
    return YES;
}
else {return NO;}
}

SO here is the use cases:

  • if I have wifi connection** : returns YES as expected.
  • If I have cellular connection : returns YES as expected.
  • If cellular and Wifi is disabled : returns NO as expected.
  • If I have WiFi connection; but the DSL cable is unplugged (so the host shouldn't be reachable, internet connection is not available.) : returns YES and it's unexpected.
  • Also if cellular is enabled but at my current position I have no signal : returns YES and it's unexpected.

How can I solve these unexpected results? Thank you.


Solution

  • With @Martin Koles' help I added a html file into the server. It only has a random value inside. Now I check reachability. If server is reachable, I am trying to get the value from html file. Than, if I could get the value returning YES. If I couldn't (the serverValue should be nil) returning NO..

    -(BOOL)checkConnection{
    Reachability *reachability = [Reachability reachabilityWithHostName:@"www.izmirmobil.com"];
    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
    if (remoteHostStatus != NotReachable) {
        NSURL *url = [NSURL URLWithString:@"http://www.example.com/getAValue.html"];
        NSError *errr = nil;
        NSStringEncoding enc;
        NSString *serverValue = [[NSString alloc] initWithContentsOfURL:url usedEncoding:&enc error:&errr];
        if(serverValue)return YES;
        else return NO;
    
    }
    else {return NO;}
    }