iOS 网络监听

网络监听使用APPLe的 

Reachability

需要添加这个文件包

同时还要添加框架:SystemConfiguration.framework


代码:

@property (retain,nonatomic)Reachability *WIFIreach;


//初始化
    self.WIFIreach = [Reachability reachabilityForInternetConnection];
    //或者:self.WIFIreach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ;
    //开始监听,会启动一个run loop  
    [self.WIFIreach startNotifier];

    //接收网络环境变化的通知  消息名称(固定)为:kReachabilityChangedNotification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

-(void) reachabilityChanged :(NSNotification *) notification
{
    Reachability *curr = [notification object];
    if ([curr isMemberOfClass:[Reachability class]]) {
         [self showState];
//        NetworkStatus state = [curr currentReachabilityStatus];
//        NSString *stateDesc;
//        switch (state) {
//            case NotReachable :
//                stateDesc = @"无可用连接";
//                [self.switch3G setOn:NO animated:YES];
//                [self.switchWIFI setOn:NO animated:YES];
//                break;
//            case ReachableViaWiFi :
//                stateDesc = @"WIFI";
//                [self.switch3G setOn:NO animated:YES];
//                [self.switchWIFI setOn:YES animated:YES];
//                break;
//            case ReachableViaWWAN :
//                stateDesc = @"2G/3G";
//                [self.switch3G setOn:YES animated:YES];
//                [self.switchWIFI setOn:NO animated:YES];
//                break;
//                
//        }
//        self.textField.text = stateDesc;
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [self showState];
}
-(void) showState
{
    //检查当前网络状态
    Reachability *currentReachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    NetworkStatus state = [currentReachability currentReachabilityStatus];
    NSString *stateDesc;
    switch (state) {
        case NotReachable :
            stateDesc = @"无可用连接";
            [self.switch3G setOn:NO animated:YES];
            [self.switchWIFI setOn:NO animated:YES];
            break;
        case ReachableViaWiFi :
            stateDesc = @"WIFI";
            [self.switch3G setOn:NO animated:YES];
            [self.switchWIFI setOn:YES animated:YES];
            break;
        case ReachableViaWWAN :
            stateDesc = @"2G/3G";
            [self.switch3G setOn:YES animated:YES];
            [self.switchWIFI setOn:NO animated:YES];
            break;
            
    }
    self.textField.text = stateDesc;
    
    

}


Demo下载 http://download.csdn.net/detail/aa741649143/6210755
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值