How to check Newtwork Reachability in iOS

H

First Download Reachability files from here:
Click Here

Step 1: write below code in AppDelegate.h file.

#import “Reachability.h”
@class Reachability;

//Rechability
int internetconnectioncheck;
Reachability *internetReachable;
Reachability *hostReachable;
UIAlertView *internetalert;

BOOL Net_chkFlag;
@property BOOL Net_chkFlag;

Step 2: write below code in AppDelegate.m file. file in didFinishLaunchingWithOptions method
@synthesize Net_chkFlag;

NSString *urltest = [[NSString alloc] initWithFormat:@”http://www.google.com”];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(checkNetworkStatus:)
name:kReachabilityChangedNotification object:nil];

internetReachable = [[Reachability reachabilityForInternetConnection] retain];
[internetReachable startNotifier];

hostReachable = [[Reachability reachabilityWithHostName:urltest ] retain];
[hostReachable startNotifier];

Step 3: Wite below method in AppDelegate.h

– (void) checkNetworkStatus:(NSNotification *)notice
{
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];

switch (internetStatus)
{
case NotReachable:
{
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;

//mainDelegate.internetconnectioncheck = 1;
//if (mainDelegate.internetconnectioncheck == 1)
//{
// to stop it, set this to NO
Net_chkFlag = FALSE;
internetalert = [[UIAlertView alloc] initWithTitle:@”INTERNET CONNECTION REQUIRED”
message:@”Connect to the internet and try again”
delegate:self
cancelButtonTitle:@”OK”
otherButtonTitles:nil,nil];

[internetalert show];
//}

break;
}
case ReachableViaWiFi:
{
// NSLog(@”The internet is working via WIFI.”);
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;

Net_chkFlag = TRUE;
break;
}
case ReachableViaWWAN:
{
// NSLog(@”The internet is working via WWAN.”);

UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;
Net_chkFlag = TRUE;

break;
}
}
}

Step 4: You can check in any view controller

Delegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];

if(Delegate.Net_chkFlag == TRUE)
{
NSString *urlcheReq = [NSString stringWithFormat:@”http://demos.Domain.com/contactus.php”];
urlcheReq = [urlcheReq stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@”%@”,urlcheReq);
}

About the author

mayur.bhansali
By mayur.bhansali

Category