网络判断

用户在使用APP的时候,有可能并不知道,或者是忘记自己当前的网络状况, 导致用流量看视频等特别费流量的内容, 为了避免这种情况, 我们可以在惨剧发生之前,提示一下用户,当前的网络状况, 防患于未然,网络状况分为三种:
 NotReachable   //无连接
 ReachableViaWiFi  //使用3g/4g等手机自带网络
 ReachableViaWWAN  //使用WiFi网络

1. 首先导入Reachability.h和Reachability.m文件



2. 在要进行网络判断的页面导入Reachability.h头文件

#import "Reachability.h"

3.在你要判断网络的地方,设置一个监听,这里,我写在viewDidLoad里, 大家可随意

- (void)viewDidLoad {

    [super viewDidLoad];

//

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

    self.conn = [Reachability reachabilityForInternetConnection];

    //Reachability对象开启被监听状态

    [self.conn startNotifier];

// 这个方法根据自己需求调用, 当你希望一开始到这个页面就判断网络的话, 可以调用这个方法, 如果只是希望网络变化的情况下,可以不调用.

    [self checkNetworkState];

}

- (void)dealloc

{

    [self.conn stopNotifier];

    [[NSNotificationCenter defaultCenter] removeObserver:self];

    

}

- (void)networkStateChange

{

    

     [self checkNetworkState];

    

}

- (void)checkNetworkState

{

    // 1.检测wifi状态

    Reachability *wifi = [Reachability reachabilityForLocalWiFi];

    

    // 2.检测手机是否能上网络(WIFI\3G\2.5G)

    Reachability *conn = [Reachability reachabilityForInternetConnection];

    // NSLog(@"44");

    

    // 3.判断网络状态

    // currentReachabilityStatus方法获取网络连接状态,如果网络连接状态返回NotReachable,则表明这种类型的网络暂未连接。

    // WiFi 和手机网络 WiFi

    // 没有WiFi用手机网络

    // 没网络 没有 网络

    if ([wifi currentReachabilityStatus] != NotReachable) {

        // wifi

        // if (self.isNet == NO) {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"WiFi" message:@"请放心使用" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];

        [alert show];

        

        

        //   }

        

    } else if ([conn currentReachabilityStatus] != NotReachable) {

        // 没有使用wifi, 使用手机自带网络进行上网

        NSLog(@"使用手机自带网络进行上网(2g/3g/4g)");

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"使用手机自带网络进行上网(2g/3g/4g" message:@"请注意流量" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];

        [alert show];

        

        

    } else

// 没有网络

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"没有网络" message:@"请检查网络" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];

        [alert show];

        

    }

    

    

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值