Use of tonymillion/Reachability, reachability
Tonymillion/ReachabilityIs an open-source tool class on GitHub. The visual view is rewritten based on Apple's Reachability Demo.
This class can be used to test the accessibility of a network or host. It supports Block syntax and network connection status monitoring, which is very practical. For specific usage, refer to the instructions on GitHub.
I wrote a Demo and tried it:
- (void)viewDidLoad { [super viewDidLoad]; UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; [button setTitle:@"Listen" forState:UIControlStateNormal]; [button addTarget:self action:@selector(reachable) forControlEvents:UIControlEventTouchUpInside]; button.frame = CGRectMake(0, 0, 100, 44); button.center = self.view.center; [self.view addSubview:button];}- (void)reachable { Reachability *reach = [Reachability reachabilityWithHostname:@"www.csdn.net"]; reach.reachableBlock = ^(Reachability *reachability) { NSLog(@"Reachable"); }; reach.unreachableBlock = ^(Reachability *reachability) { NSLog(@"Unreachable"); }; [reach startNotifier];}
Run, click the Listen button (only one click during the test), disconnect the wifi or network cable, connect to the device again, and then disconnect and perform the test again and again...
The console output is as follows:
2014-07-24 23:35:54.669 ReachabilityDemo[2247:80409] Reachable2014-07-24 23:35:59.797 ReachabilityDemo[2247:80409] Unreachable2014-07-24 23:36:07.401 ReachabilityDemo[2247:80788] Reachable2014-07-24 23:36:07.421 ReachabilityDemo[2247:80788] Reachable2014-07-24 23:36:11.279 ReachabilityDemo[2247:80788] Unreachable2014-07-24 23:36:17.523 ReachabilityDemo[2247:80964] Reachable2014-07-24 23:36:17.541 ReachabilityDemo[2247:80964] Reachable
You can see that as long as reach starts to listen to the network status, this class will always listen to its status.
If you want to perform any processing actions in the reachableBlock and unreachableBlock only once, do not create multiple Reachability instances for listening. Otherwise, the actions in the same Block may be executed multiple times.
After the action to be completed is completed, stop listening, so that both blocks will not be executed. For example:
reach.reachableBlock = ^(Reachability *reachability) { NSLog(@"Reachable"); // Do something only once while reachable [reachability stopNotifier]; };
Run again, click the Listen button, disconnect wifi, connect to wifi, and repeat...
The console output is as follows:
2014-07-24 23:50:56.814 ReachabilityDemo[2453:88238] Reachable
The Block is executed only once.