标签:
#import "ViewController.h"
#import "Reachability.h"
//注:工程需要引入Reachability.h 与 Reachability.m
@interface ViewController ()
@property(nonatomic,strong)Reachability *reach;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 判断能否连接到某一个主机
self.reach = [Reachability reachabilityWithHostName:@"baidu.com"];
// 添加通知 监测网络状态
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged) name:kReachabilityChangedNotification object:nil];
// 开始监听
[self.reach startNotifier];
}
- (void)dealloc
{
// 停止监听
[self.reach stopNotifier];
// 移除监听 // 移除整个控制器里所有的监听
// [[NSNotificationCenter defaultCenter] removeObserver:self];
// 移除控制器里的kReachabilityChangedNotification监听
[[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}
- (void)reachabilityChanged
{
// 网络状态
switch (self.reach.currentReachabilityStatus) {
case NotReachable:
NSLog(@"没有连接");
break;
case ReachableViaWiFi:
NSLog(@"WiFi");
break;
case ReachableViaWWAN:
NSLog(@"WWAN");
break;
default:
NSLog(@"无");
break;
}
}
@end
标签:
原文地址:http://www.cnblogs.com/zhang1015/p/4802255.html