网络检测

导入头文件

#import "Reachability.h"

创建属性

@property(nonatomic,strong)Reachability *reachli; //网络检测

创建网络检测对象

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    //创建网络检测对象
    self.reachli = [Reachability reachabilityForInternetConnection];

创建通知 并且添加通知

    //创建通知   并且添加通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(change) name:kReachabilityChangedNotification object:nil];
    
    //开始监听网络状态
    [self.reachli startNotifier];
    //调用change方法
    [self change];
    
}
//接受到通知   网络状态改变  调用
-(void)change{
    
    //创建网络连接状态对象
    NetworkStatus status = [self.reachli currentReachabilityStatus];
    
    //判断网络状态
    switch (status) {
        case NotReachable:{
            NSLog(@"没有网络");
            UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"网络提示" message:@"没有网络链接" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            //展示提示框
            [aler show];
            break;
        }
        case ReachableViaWiFi:{
            NSLog(@"链接成功");
            UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"网络提示" message:@"链接到Wifi" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            //展示提示框
            [aler show];
            break;
            
        }
        case ReachableViaWWAN:{
            NSLog(@"链接到蜂窝");
            UIAlertView *aler = [[UIAlertView alloc]initWithTitle:@"网络提示" message:@"链接到蜂窝" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            //展示提示框
            [aler show];
            break;
        }
            
            
            
        default:
            break;
    }
    
}
-(void)dealloc{
    //停止网络监听
    [self.reachli stopNotifier];
    //移除通知
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

你可能感兴趣的:(网络检测)