Search code examples
iphoneobjective-creachability

Iphone internet connection (Reachability)


I saw any post about Reachability but people doesn't really give the exact answer to the problem. In my application I use the Reachability code from apple and in my appDelegate I use this:


-(BOOL)checkInternet {

Reachability *reachability = [Reachability reachabilityWithHostName:@"www.google.com"];

NetworkStatus internetStatus = [reachability currentReachabilityStatus];
BOOL internet;

if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
    internet = NO;
}else {
    internet = YES;
}
return internet;    
}

So the problem is even if I have an internet connection, this code telling me that I don't have one. Does anyone know what to do to make this working?

Thanks,


Solution

  • You should probably be using +[Reachability reachabilityForInternetConnection] rather than reachability for a particular name (unless of course that's what you actually need).

    There could be all manner of reasons that a particular server might not be reachable while you still have a working internet connection, after all.

    This is what I do:

    BOOL hasInet;
    Reachability *connectionMonitor = [Reachability reachabilityForInternetConnection];
    [[NSNotificationCenter defaultCenter]
        addObserver: self
        selector: @selector(inetAvailabilityChanged:)
        name:  kReachabilityChangedNotification
        object: connectionMonitor];
    
    hasInet = [connectionMonitor currentReachabilityStatus] != NotReachable;
    

    and then

    -(void)inetAvailabilityChanged:(NSNotification *)notice {
        Reachability *r = (Reachability *)[notice object];
        hasInet = [r currentReachabilityStatus] != NotReachable;
    }
    

    which works nicely for me.