iOS 检测网络状态

1.为什么要检测网络状态?

1.1 让用户知道自己的网络状态,防止用户埋怨"这个应用太垃圾,获取数据那么慢"

1.2 根据用户的网络状态,智能处理,提升用户体验

例如某些手机浏览器,检测到用户网络是2G/3G时,会自动切换为无图模式

2.手动触发

2.1 首先下载苹果的示例程序Reachability, 取得示例程序里的Reachability.h和Reachability.m, 添加到自己项目里

代码如下

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

    // 检测WIFI状态

    Reachability *WIFI = [Reachability reachabilityForLocalWiFi];

    // 检测手机联网状态(2G/3G/WIFI)

    Reachability *conn = [Reachability reachabilityForInternetConnection];

    

    if ([WIFI currentReachabilityStatus] != NotReachable) { //有WIFI

        NSLog(@"当前连着WIFI");

    }else{ //无WIFI

        if ([conn currentReachabilityStatus] != NotReachable) { //有2G/3G网络

            NSLog(@"当前连着2G/3G网络");

        }else{ //无2G/3G网络

            NSLog(@"当前没联网");

        }

     }

}

 

2.2 实际应用中,不会让用户手动去检测网络状态,下面用通知实现实时检测网络状态

@property (nonatomic,strong) Reachability *coon;

   // 添加通知

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

    self.coon = [Reachability reachabilityForInternetConnection];

    // 发送通知

    [self.coon startNotifier];

 

- (void)dealloc

{

    [self.coon stopNotifier];

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

- (void)networkChange

{

    [self checkNetworkState];

}

 

- (void)checkNetworkState

{

    Reachability *WIFI = [Reachability reachabilityForLocalWiFi];

    Reachability *conn = [Reachability reachabilityForInternetConnection];

    if ([WIFI currentReachabilityStatus] != NotReachable) { //有WIFI

        NSLog(@"当前连着WIFI");

    }else{ //无WIFI

        if ([conn currentReachabilityStatus] != NotReachable) { //有2G/3G网络

            NSLog(@"当前连着2G/3G网络");

        }else{ //无2G/3G网络

            NSLog(@"当前没联网");

        }

    }

}

转载于:https://www.cnblogs.com/oumygade/p/4245349.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值