这里需要下载一个第三方
Reachability-master
大家可以百度一下
下载之后把
Reachability拖进来
具体代码如下
1 #import "ViewController.h" 2 #import "Reachability.h" 3 4 @interface ViewController () 5 6 @property (nonatomic, strong) Reachability * reach; 7 @end 8 9 @implementation ViewController 10 11 - (void)viewDidLoad { 12 [super viewDidLoad]; 13 // Do any additional setup after loading the view, typically from a nib. 14 15 //根据主机名判断网络是否连接 16 self.reach=[Reachability reachabilityWithHostName:@"www.baidu.com"]; 17 //注册网络监听通知 18 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged) name:kReachabilityChangedNotification object:nil]; 19 //开启监听 20 [self.reach startNotifier]; 21 } 22 23 - (void)reachabilityChanged { 24 25 switch (self.reach.currentReachabilityStatus) { 26 case NotReachable: 27 NSLog(@"没有网络"); 28 break; 29 case ReachableViaWiFi: 30 NSLog(@"WiFi网络"); 31 break; 32 case ReachableViaWWAN: 33 NSLog(@"移动蜂窝网"); 34 break; 35 default: 36 NSLog(@"未知网络"); 37 break; 38 } 39 40 } 41 - (void)dealloc { 42 43 //把当前的对象所有通知删除 44 45 [[NSNotificationCenter defaultCenter] removeObserver:self]; 46 [self.reach stopNotifier]; 47 }