如何判断网络

我这里做判断网络使用的是一个第三方库:Reachability
大家可以直接在gitHup搜索下载;

下载之后添加到你所需要的工程中就可以了

下面上代码:
我的ViewController.h什么也没有声明

#import "ViewController.h"
#import "Reachability.h"
@interface ViewController ()
@property(nonatomic,strong)Reachability *reach;

@property(nonatomic,strong)UILabel *lable;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    _lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 300, 100)];
    _lable.center = self.view.center;
    
    _lable.font = [UIFont systemFontOfSize:50];
    
    _lable.textColor = [UIColor blackColor];
    
    [self.view addSubview:_lable];
    
    _reach = [Reachability reachabilityForInternetConnection];
    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(netInter) name:kReachabilityChangedNotification object:nil];

    [_reach startNotifier];
    
    
    [self panduan];
    
}


-(void)panduan{
    
    Reachability *reachable = [Reachability reachabilityForInternetConnection];
    
    if ([reachable currentReachabilityStatus] == ReachableViaWiFi) {
        NSLog(@"wifi - 已连接");
        
        _lable.text = @"wifi - 已连接";
        
    } else if ([reachable currentReachabilityStatus] == ReachableViaWWAN) {
        NSLog(@"数据 - 已连接");
        
        _lable.text = @"数据 - 已连接";
        
        
    } else {
        NSLog(@"无网络连接");
        
         _lable.text = @"无网络连接";
        
    }
    
    
    
}



-(void)netInter{
    
    
    if (self.reach.currentReachabilityStatus == ReachableViaWiFi) {
        _lable.text = @"123Wifi";
        
        
    }else if (self.reach.currentReachabilityStatus == ReachableViaWWAN){
        
        _lable.text = @"数据";
        
        
    }else{
        
        
        _lable.text = @"无网络";
        
        
    }
    
    
    
}


-(void)dealloc{
    
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

你可能感兴趣的:(如何判断网络)