Reachability网络情况之详解


Reachability判断网络情况

// 把Reachability声明成属性

@property (strong , nonatomic ) Reachability *reach;


//网络监听实现
-(void)setNetNotice
{

     //开启网络状况监听 测试服务器状态
    self.reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    
    [self.reach startNotifier];//开始监听.会启动一个run loop  kReachabilityChangedNotification
    

}


//通知
- (void)reachabilityChanged:(NSNotification *)note{

   self.reach = [note object];

    NSParameterAssert([self.reach isKindOfClass:[Reachability class]]);

    NetworkStatus status = [self.reach currentReachabilityStatus];

    // 网络没有连接时
    if(status == NotReachable){

     // 弹出提示框

        UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:nil message:@"网络已断开" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];

        [alterView show];
     
    }else if(status == ReachableViaWWAN){ // 使用流量时

        UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:nil message:@"当前为2G/3G网络,请注意流量" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];

        [alterView show];
     
    }else if(status == ReachableViaWiFi){ // 链接wifi时

        UIAlertView *alterView = [[UIAlertView alloc]initWithTitle:nil message:@"当前为WiFi网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];

        [alterView show];
     
    }
}


你可能感兴趣的:(Reachability网络情况之详解)