tonymillion/Reachability是GitHub上的一个开源工具类,目測是依据Apple的Reachability Demo改写而成。
该类能够測试到某一网络、主机等的可达性,支持Block语法和监听网络连接状态,很有用。详细使用方法參加GitHub上的说明。
写了个小Demo试用了一下:
- (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,点击Listenbutton(整个測试过程仅仅点击一次),然后断开wifi或网线。然后又连上,然后又断开,重复測试。。
。
控制台输出例如以下:
2014-07-24 23:35:54.669 ReachabilityDemo[2247:80409] Reachable 2014-07-24 23:35:59.797 ReachabilityDemo[2247:80409] Unreachable 2014-07-24 23:36:07.401 ReachabilityDemo[2247:80788] Reachable 2014-07-24 23:36:07.421 ReachabilityDemo[2247:80788] Reachable 2014-07-24 23:36:11.279 ReachabilityDemo[2247:80788] Unreachable 2014-07-24 23:36:17.523 ReachabilityDemo[2247:80964] Reachable 2014-07-24 23:36:17.541 ReachabilityDemo[2247:80964] Reachable
能够看到仅仅要reach開始监听网络状态,那么该类会一直监听其状态。
假设想要在reachableBlock和unreachableBlock中做什么处理动作。而且仅仅运行一次,就不要创建多个Reachability类实例进行监听了。否则同一个Block中的动作可能运行多次。
待要完毕的动作完毕后。停止监听即可了,这样两个Block都不会再被运行。
比如:
reach.reachableBlock = ^(Reachability *reachability) { NSLog(@"Reachable"); // Do something only once while reachable [reachability stopNotifier]; };
再Run。点击Listenbutton,断开wifi。连接wifi。反复。。。
控制台输出例如以下:
2014-07-24 23:50:56.814 ReachabilityDemo[2453:88238] Reachable
能够看到Block仅仅运行了一次。