Monitor internet connection using AFNetworking 3

Check internet connection in Objective-C

When working with server calls, it’s a good practice to use internet connection validation and check if there is a connection before calling a web service. Also, you might need it for changing the UI.

 

This snippet is monitoring the internet connection for the whole time while the user is active, you just need to trigger it from the AppDelegate:

-(void)startMonitoringInternetConnection{
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        BOOL hasInternet = (status != AFNetworkReachabilityStatusNotReachable && status != AFNetworkReachabilityStatusUnknown);
        
        if (hasInternet) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"HasInternetConnection" object:nil];
        }else{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"NoInternetConnection" object:nil];
        }
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

 

Then in the view controllers, you should create observers: 

- (void)viewDidLoad {
    [super viewDidLoad];    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hasInternetConnection) name:@"HasInternetConnection" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noInternetConnection) name:@"NoInternetConnection" object:nil];
}

-(void)hasInternetConnection{


}
-(void)noInternetConnection{

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *