断网判断

#import "ViewController.h"
#import "Reachability.h"

@interface ViewController ()
@property(nonatomic,retain)Reachability * coon;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton * checkBut = [UIButton buttonWithType:UIButtonTypeCustom];
    [checkBut addTarget:self action:@selector(handleCheck:) forControlEvents:UIControlEventTouchUpInside];
    [checkBut setTitle:@"点击检测网络" forState:UIControlStateNormal];
    [self.view addSubview:checkBut];
    checkBut.frame = CGRectMake(50, 50, 120, 20);
    
    //创建一个监控网络状态的消息中心
    NSNotificationCenter * notifyCenter = [NSNotificationCenter defaultCenter];
    [notifyCenter addObserver:self selector:@selector(checkNetWork) name:kReachabilityChangedNotification object:nil];
    self.coon = [Reachability reachabilityForInternetConnection];//
    [self.coon startNotifier];//开始检测网络
}
//检测网络的按钮
-(void)handleCheck:(UIButton *)sender{
    //检测网络是否发生变化
    [self checkNetWork];
}
//监控网络是否发生了变化
-(void)checkNetWork{
    //1检测 WiFi 的状态
    Reachability * wifi = [Reachability reachabilityForLocalWiFi];
    //2.检测手机手否能够上网(2G/3G/2.5G/Wifi)
    Reachability * conn = [Reachability reachabilityForInternetConnection];
    if ([wifi currentReachabilityStatus] != NotReachable) {//有wifi
        UIAlertView * alter = [[UIAlertView alloc]initWithTitle:@"网络检测" message:@"WiFi链接成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alter show];
        NSLog(@"检测到互联网Wifi");
    }else if ([conn currentReachabilityStatus] != NotReachable)//没使用WiFi网络,使用手机自带的网络
    {
        UIAlertView * alter = [[UIAlertView alloc]initWithTitle:@"网络检测" message:@"手机自带的网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alter show];
        NSLog(@"检测到互联网本地网络");
    }else{
        NSLog(@"没有检测到互联网");
    }
    //使用 wifi
//    [wifi currentReachabilityStatus] != NotReachable;
//    [conn currentReachabilityStatus] != NotReachable;
    //使用的是本地的网络
//    [wifi currentReachabilityStatus] == NotReachable;
//    [conn currentReachabilityStatus] != NotReachable;
    //没有网络
//    [wifi currentReachabilityStatus] != NotReachable;
//    [conn currentReachabilityStatus] != NotReachable;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

-(void)dealloc{
    [self.coon stopNotifier];
    //移除消息的通知者
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
 检测网络,我用的是 pod引入的第三方网络检测类 Reachability类
原文地址:https://www.cnblogs.com/benpaobadaniu/p/5237125.html