Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up reachability with AFNetworking 2.0

I am trying to setup Reachability using the new 2.0 AFNetworking.

In my AppDelegate I initialise the sharedManager.

// Instantiate Shared Manager
[AFNetworkReachabilityManager sharedManager];

Then in the relevant VC method I check to see if isReachable:

// Double check with logging
if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
    NSLog(@"IS REACHABILE");
} else {
    NSLog(@"NOT REACHABLE");
}

At present this is not working as expected in the simulator, but I imagine this would need to be tested on device and not simulator.

Question What I would like to do is monitor the connectivity within the VC. So I run the following in the viewDidLoad:

// Start monitoring the internet connection
[[AFNetworkReachabilityManager sharedManager] startMonitoring];

How would I then register for the changes? What is/would be called once the network connection changes I cannot see this from the documentation.

like image 429
StuartM Avatar asked Nov 17 '13 20:11

StuartM


2 Answers

As you can read in the AFNetworking read me page

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
}];

Here's also a link to the official documentation.

like image 114
Gabriele Petronella Avatar answered Oct 19 '22 19:10

Gabriele Petronella


I have a singleton AFHTTPRequestOperationManager class. In the singleton has a method:

+(void)connectedCompletionBlock:(void(^)(BOOL connected))block {

[[AFNetworkReachabilityManager sharedManager] startMonitoring];

[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

    BOOL con = NO;
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));

    if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {

        con = YES;
    }

    if (block) {
        [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
        block(con);
    }

}];

}

Before make a request you call this method that return a block indicating if internet is reachable:

[TLPRequestManager connectedCompletionBlock:^(BOOL connected) {
    if (connected) {

       // Make a request

    }else{

        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Notice" message:@"Internet is not available." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];

        [alertView show];

    }

}];
like image 38
Marlon Ruiz Avatar answered Oct 19 '22 17:10

Marlon Ruiz