Reachability monitoring with AFNetworking only on the presented controller

I am using AFNetworking 2.0 to track 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; } }]; 

In addition to this main VC, I load different controllers / paths / navigation controllers and fire them as soon as they are used.

Question What I'm trying to do is monitor the connection, but only when the main VC is displayed. For example, if I load the navigation controller over the main VC and the connection is lost, I still get a reachabilityNotReachableAlert call.

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

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

+6
source share
1 answer

Unfortunately no, there is no simpler way to do this.

However, the plan you talked about doesn't sound so bad. You essentially ask the manager to turn off and turn off notifications, and you need to say when to do it.

Here is how I do it:

 - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [manager startMonitoring]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [manager stopMonitoring]; } 
+2
source

Source: https://habr.com/ru/post/958400/


All Articles