Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monitoring Reachability with AFNetworking only on a presented controller

I am using AFNetworking 2.0 to monitor Reachability.

In the viewDidLoad of my main VC I have the following:

// Start monitoring the internet connection
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));

    // Check the reachability status and show an alert if the internet connection is not available
    switch (status) {
            case -1:
                // AFNetworkReachabilityStatusUnknown = -1,
                NSLog(@"The reachability status is Unknown");
                [self reachabilityNotReachableAlert];
            case 0:
                // AFNetworkReachabilityStatusNotReachable = 0
                NSLog(@"The reachability status is not reachable");
                [self reachabilityNotReachableAlert];
            case 1:
                // AFNetworkReachabilityStatusReachableViaWWAN = 1
                NSLog(@"The reachability status is reachable via WWAN");
            case 2:
                // AFNetworkReachabilityStatusReachableViaWiFi = 2
                NSLog(@"The reachability status is reachable via WiFi");
            break;

        default:
            break;
    }

}];

On top of this main VC I load different view controllers/paths/navigation controllers and dismiss once they have been used.

Question What I am trying to do is monitor the connection but only when the main VC is displayed. For example, if I load a navigation controller on top of the main VC and the connection is lost I would still get the call to the reachabilityNotReachableAlert.

How can I only monitor when the main VC is displayed on screen, without having to run stopMonitoring and startMonitoring all the time?

I guess I can put the stopMonitoring in the prepareForSegue method and then startMonitoring in the viewDidAppear, is there not an easier way to do this?

like image 720
StuartM Avatar asked Nov 19 '13 14:11

StuartM


1 Answers

Unfortunately no, there isn't an easier way to do this.

However, the plan you mentioned doesn't sound all that bad. You essentially are asking the manager to turn it's notifications off and on, and it needs you to tell it when to do so.

Here's how I do it:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [manager startMonitoring];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [manager stopMonitoring];
}
like image 102
djibouti33 Avatar answered Nov 07 '22 04:11

djibouti33