in ios, mobile, objective c

Network Reachability Test and HTTP Call with AFNetworking

There are plenty of time when we need to have active internet connection for an mobile application to be used. So it is always good idea to check internet connection before the application get ready for use.

AFNetworking is one of the best iOS library out there for making HTTP request for accessing web services.  Same library is good enough for checking active internet connection. So now let’s dive into how we can constantly monitor the internet connection throughout the application.

 

1.  Set up AFNetworking


Using Pods.

pod ‘AFNetworking’‘~> 2.4’

2. Helper Class to make HTTP connection and checking


Now it is time to start developing code snippet. First create a NSObject Class  named “HTTPRequestHandler”.  And start adding following code in .m file.

It is always good idea to use key value observer in iOS for constantly monitoring changes in Objects.  So below is the code that will register an observer  key

AFNetworkingReachabilityDidChangeNotification available in AFNetworking.

+(void) startMonitoringInternetConnectivity{

    [[NSNotificationCenter defaultCenteraddObserverself

                                          selector:@selector(reachabilityChanged:)

                                          nameAFNetworkingReachabilityDidChangeNotification

                                          object:nil];

    [[AFNetworkReachabilityManager sharedManagerstartMonitoring];

}

 

After the invocation of  startMonitoring, AFNetworking will start monitoring the internet availability.   If it found any change in the internet availability thenreachabilityChanged method get called.  This is the place where we need to setup internet connection boolean value to true or false. For this we need to create Boolean variable in AppDelegate Class and let’s name it  networkReachability.

+(void) reachabilityChanged: (NSNotification *) nofitifation

{

    NSLog(@”Reachability Test Invoked”);

 

    AppDelegate *delegate = (AppDelegate *) [[UIApplication sharedApplicationdelegate];

    switch ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus) {

        case AFNetworkReachabilityStatusReachableViaWWAN:

        case AFNetworkReachabilityStatusReachableViaWiFi:

        {

            NSLog(@”Reachability Test Passed”);

            delegate.networkReachability =TRUE;

 

        }

            break;

        case AFNetworkReachabilityStatusNotReachable:

        case AFNetworkReachabilityStatusUnknown:

        {

            NSLog(@”Reachability Test Failed”);

            delegate.networkReachability=FALSE;

}

            break;

        default:delegate.networkReachability=FALSE;

                break;

}

 

}

Once you add observer in your application, it is your responsibility to remove observer when it is not in the state of use.

+(void)  stopMonitoringInternetConnectivity{

    [[AFNetworkReachabilityManager sharedManagerstopMonitoring];

    [[NSNotificationCenter defaultCenter]removeObserver:self name:AFNetworkingReachabilityDidChangeNotification object:nil];

}

3. Initiate internet connection check service


This one is most tricky part of this tutorial.  Application can enter into active state from background to foreground state or by lunching.  Similarly application can enter into background  by terminating app or switching to other application. In both of the state there are 2 thing that is common. Application will invoke   applicationDidBecomeActive when user open up the application by any case. Similarly applicationWillResignActive will get invoked when user close the application.  So insert below code at respected place.

– (void)applicationDidBecomeActive:(UIApplication *)application {

    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    NSLog(@”Application did become active”);

    [HTTPRequestHandler startMonitoringInternetConnectivity];

}

– (void)applicationWillResignActive:(UIApplication *)application {

    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

     NSLog(@”applicationWillResignActive”);

    [HTTPRequestHandler stopMonitoringInternetConnectivity];

 

}

4. Making HTTP Request


Add Following HTTPGet Request  Handler in HTTPRequestHandler.m. This method  have four parameter that need to be passed while  making a call.

  1. URL: Url  to make http request.
  2. Request Parameter: Get parameter needed to be passed with url.
  3. Selector Name: Method name that will get invoked on successful http call.
  4. Target: Class instance where the selector is defined.

+(void) HTTPGetRequest:(NSString *) stringURL andParameter:(NSDictionary *) parameter andSelector:(SEL) selector andTarget:(id) target{

    NSLog(@”Sending Request to:%@ with parameter:%@”,stringURL, parameter);

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    [manager GET:stringURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

 

        NSLog(@”HTTP Respons :%@”,[self convertToString:responseObject]);

        [target performSelectorOnMainThread:selector withObject:responseObject waitUntilDone:YES];

        }

    failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        NSLog(@”Error: %@”, error);

        [target performSelectorOnMainThread:@selector(requestError:) withObject:error waitUntilDone:YES];

 

        }];

}

Since we have already started observing internet connection in AppDelegate, It’s now very easy  to decide where we can start making HTTP request or not. For this we just need to check AppDelegate.networkReachability value to TRUE or FALSE. So in any view controller use following code snippet to make http call

{

if ([HTTPRequestHandler checkInternetAvailability]) {

        [HTTPRequestHandler HTTPGetRequest:@”http://google.com andParameter:nil andSelector:nil andTarget:self];

    }

    else{

        NSLog(@”offline mode”);

    }

}

Write a Comment

Comment

Webmentions

  • sahabat qq

    … [Trackback]

    […] Here you can find 53827 additional Information on that Topic: rajantwanabashu.com.np/mobile/2016/09/20/network-reachability-test-and-http-call-with-afnetworking/ […]

  • post

    … [Trackback]

    […] Read More Information here on that Topic: rajantwanabashu.com.np/mobile/2016/09/20/network-reachability-test-and-http-call-with-afnetworking/ […]