标签:style http color 使用 os strong io 2014
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];
}控制台输出如下:
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
如果想要在reachableBlock和unreachableBlock中做什么处理动作,并且只执行一次,就不要创建多个Reachability类实例进行监听了,否则同一个Block中的动作可能执行多次。
待要完成的动作完成后,停止监听就行了,这样两个Block都不会再被执行。例如:
reach.reachableBlock = ^(Reachability *reachability) {
NSLog(@"Reachable");
// Do something only once while reachable
[reachability stopNotifier];
};再Run,点击Listen按钮,断开wifi,连接wifi,重复。。。
控制台输出如下:
2014-07-24 23:50:56.814 ReachabilityDemo[2453:88238] Reachable
可以看到Block只执行了一次。
tonymillion/Reachability的使用,布布扣,bubuko.com
标签:style http color 使用 os strong io 2014
原文地址:http://blog.csdn.net/jymn_chen/article/details/38097743