goelv
goelv

Reputation: 1039

How do I use Apple's Reachbility in conjunction with NSURLConnection or NSURLSession?

Across my app I am using NSURLConnection to make any server related API Calls.

I am using the function NSURLConnection sendAsynchronousRequest queue completionHandler to make async requests to the server. Sometimes these requests fail because there is no internet connection.

How would I use Apple's Reachability Class in conjunction with NSURLConnection?

Upvotes: 0

Views: 66

Answers (2)

dgatwood
dgatwood

Reputation: 10417

The correct way to use reachability is as follows:

  1. Make the request.
  2. If it fails, create a reachability listener for the specific host that you're trying to reach (reachabilityWithHostName:).
  3. When that class indicates that reachability has changed, check to see if it says that it is now reachable, and if so, dispose of the reachability object and re-issue the request.

What you absolutely should not do is gate the initial request on reachability. The reachability APIs can get out of sync with reality, causing your app to fail to make requests that would otherwise have succeeded.

It is, however, acceptable to limit the retry rate of periodic requests based on overall reachability. However, if any of those requests succeeds, your app should then act as though reachability gave it a green light even if it didn't.

Upvotes: 0

Psykie
Psykie

Reputation: 176

You just need to do that:

Reachability *reachability = [Reachability reachabilityForInternetConnection];    
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if (internetStatus != NotReachable) {
    // connection ok: call NSURLConnection sendAsynchronousRequest queue completionHandler here
}
else {
    // No connection
}

Be careful to check if the network is provided by wifi or not before download big data. You can check this through the internetStatus.

Upvotes: 1

Related Questions