KkMIW
KkMIW

Reputation: 1112

Check before calling webservice internet is On or Off

Want to check is Internet is available or not-available before calling any WEB-SERVER.

I used the Reachiablity which provided by apple to check the internet is on or off. I added this two files into my project. Reachability.h and Reachability.m

In ViewController.h

 -(BOOL)connected;

and ViewController.m its Implementation.

   -(BOOL)connected{
        Reachability *reachability = [Reachability reachabilityForInternetConnection];
        NetworkStatus networkStatus = [reachability currentReachabilityStatus];
        return networkStatus != NotReachable;
    }

before calling webserver making an condtion

if([self connection] == true){

// Do call web server.
}

else {
// Alert message print. // Please check internet connection.
}

When running the application in both case with WIFI ON or OFF with MACBOOKPRO "Simulator" or on Device. Its always returns true condition.

Please let me know, what should i need to do properly for making reachablity work.

I am using Xcode 6.0.1 IOS SDK 8.0.

@ALL Thank In Advance.

Upvotes: 1

Views: 879

Answers (4)

pankaj asudani
pankaj asudani

Reputation: 852

try the following code:

if (![self connected]) {

   // Alert message print. // Please check internet connection.
 } else {
  // Do call web server.
}

Upvotes: 0

gabbler
gabbler

Reputation: 13766

I did a test on iOS 8, the above code works on device. But on simulator, it is always returns true no matter wifi is on or off. After changing the reachability to:

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

it worked on simulator.

The original code works on simulator with iOS 7. So possibly a bug for iOS 8.

Upvotes: 0

jrturton
jrturton

Reputation: 119242

Why bother? If there's no network connection, you'll get a perfectly good error back from your attempt. Reachability is useful for knowing when a connection has returned, if you had network jobs queued up, but it's pointless to check before every web call.

You need error handling code anyway, because a missing connection is only one of several reasons a request could return an error. In this case reachability is adding extra code for no benefit, which is true of most uses I've seen.

Upvotes: 1

Sandeep
Sandeep

Reputation: 776

If you use AFNetworking library then it internaly check network connection and gives proper network error alerts. REF: http://afnetworking.com

Upvotes: 0

Related Questions