Mayank Jain
Mayank Jain

Reputation: 5754

How to detect internet connection when connected to wifi but no intenernet: iOS

I just want to know how to detect internet connectivity in iOS when device is connected to wifi but no intenet connection in modem.

I have used apple's and AFNetworking's reachability but they only check for connectivity and returns connected flag even there is no working internet in modem.

Upvotes: 5

Views: 990

Answers (2)

ddb
ddb

Reputation: 2435

In order to be sure that your device is really connected to internet, at least you have to try a ping to a up&running at anytime server (like stackoverflow.com o google.com).

Of course, as suggested by @jonrsharpe in question's comments, if this check is necessary in order to understand if app can reach the web server, then a ping or something like that to your web server is also necessary.

But a ping to a surely working web server (like google) will give you the answer it your device is connected to internet (so your modem can reach internet), that way if your web server is not responding you can accordingly show a warning alert in your app to inform user that currently your server is unreachable.

Going to code, you can try to check connection status with Reachability library like below

Reachability *reachability = [Reachability reachabilityWithHostName:@"stackoverflow.com"];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];

and then check networkStatus variable: if 0 you don't have access to internet, otherwise YES, so

if(networkStatus==0) {
    // no access to internet
} else {
    // you have access to internet
}

Upvotes: 1

Mayank Jain
Mayank Jain

Reputation: 5754

I found the solution by hitting host via Reachability:-

Might be helpful for someone.

-(BOOL)isCheckConnection {
    Reachability *rc = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStatus = [rc currentReachabilityStatus];

    if(internetStatus==0)
    {
        //@"NoAccess";
        return NO;
    }
    else if(internetStatus==1)
    {
        //@"ReachableViaWiFi";
        return YES;
    } else if(internetStatus==2)
    {
        //@"ReachableViaWWAN";
        return YES;
    }
    else
    {
        //@"Reachable";
        return YES;
    }
}

Upvotes: 2

Related Questions