Here i have a very interesting topic for discussion or you can say i need a suggestion for the better approach.
Here is my code
+ (BOOL) isConnected
{
BOOL flag = TRUE;
if (![self isHostReachable])
{
flag = FALSE;
NSString* alertTitle= @"";
NSString* alertMessage= @"";
if (![self isInternetReachable])
{
alertTitle = @"Network unavailable";
alertMessage = @"We can't connect to the Internet. Check your settings/connection.";
}
else
{
alertTitle = @"Server not responding";
alertMessage = @"Server not responding at the moment. Please try again later. Sorry for inconvenience";
}
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:self
cancelButtonTitle:@"Close"
otherButtonTitles:nil];
[alert show];
}
return flag;
}
+ (BOOL) isInternetReachable
{
Reachability *netReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus netSat = [netReachability currentReachabilityStatus];
return (!(netSat == NotReachable));
}
+ (BOOL) isHostReachable
{
Reachability *hostReachability = [Reachability reachabilityWithHostname: [Connection returnHostName]];
NetworkStatus netSat = [hostReachability currentReachabilityStatus];
return (!(netSat == NotReachable));
}
In my code, I used to call the “isConnected” method in order to check the connectivity status, before asking my server for data.
In the method, I am checking the hostReachability first of all. My thinking behind doing this is to save the computation time.
- If the hostReachability returns true it implies netConnectivity is also there(no need to verify). So here we are done with just one computation.
- If the hostReachability returns false, then I am checking is it the net connectivity thats responsible for it. Hence two computations.
But it usually seen that the code first verifies the netConnectivity, if its ok, then verify the hostReachability.
So most of the times Two computations, thats in contrast with my way of getting the thing done.
Please suggest which one you think is better approach?
Well netConnectivity would verify if the network is in position and not down due to any of the 100 reasons, then the host is verified to be reachable as the server may be down due to some issue.
If the network is verified as failed connection it will rule out verifying the host in the first place. vice-versa is not true though..
I hope that was useful as explanation to you.
Cheers!!