美文网首页
iOS----获取当前网络状态

iOS----获取当前网络状态

作者: 彬至睢阳 | 来源:发表于2017-12-06 18:02 被阅读0次

    #import "NetStateViewController.h"

    @interface NetStateViewController ()

    {

    UILabel *netStatelLab;

    }

    @end

    @implementation NetStateViewController

    - (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    netStatelLab=[[UILabel alloc]initWithFrame:CGRectMake(0, 200, 400, 30)];

    netStatelLab.backgroundColor=[UIColor clearColor];

    netStatelLab.textColor=[UIColor blackColor];

    [self.view addSubview:netStatelLab];

    [self netWork];

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(netWork) userInfo:nil repeats:YES];

    [timer fire];

    }

    - (int)currentNerworkType{

    int networkType = -1;

    UIApplication *app = [UIApplication sharedApplication];//获取App

    NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];

    for (id subview in subviews) {

    if ([subview isKindOfClass:NSClassFromString(@"UIStatusBarDataNetworkItemView")]){

    networkType = [[subview valueForKeyPath:@"dataNetworkType"] intValue];

    }

    }

    return networkType;

    }

    - (void)netWork{

    int networkType = [self currentNerworkType];

    UIApplication *app = [UIApplication sharedApplication];

    NSArray *subviews = [[[app valueForKey:@"statusBar"] valueForKey:@"foregroundView"] subviews];

    if (5 == networkType) {//WIFI

    NSString *dataNetworkItemView = nil;

    for (id subview in subviews) {

    if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {

    dataNetworkItemView = subview;

    break;

    }

    }

    int signalStrength = [[dataNetworkItemView valueForKey:@"_wifiStrengthBars"] intValue];

    NSString *des = @"";

    if (signalStrength >3 || signalStrength == 3) {

    des = @"强";

    }else if (signalStrength == 2){

    des = @"中";

    }else{

    des = @"弱";

    }

    netStatelLab.text = [NSString stringWithFormat:@"WIFI  --  信号:%d格 -- %@",signalStrength,des];

    }

    else if(networkType > 0){

    NSString *signalStrengItemView = nil;

    for (id subview in subviews) {

    if ([subview isKindOfClass:[NSClassFromString(@"UIStatusBarSignalStrengthItemView") class]]) {

    signalStrengItemView = subview;

    break;

    }

    }

    int signalStrength = [[signalStrengItemView valueForKey:@"_signalStrengthBars"] intValue];

    NSString *des = @"";

    if (signalStrength >4 || signalStrength == 4) {

    des = @"强";

    }else if (signalStrength == 3){

    des = @"中";

    }else{

    des = @"弱";

    }

    netStatelLab.text = [NSString stringWithFormat:@"%dG  --  信号:%d格 -- %@",networkType+1,signalStrength,des];

    }else{

    netStatelLab.text = @"无信号";

    }

    }

    这种方法是通过监听手机的statusbar的状态来获取用户的网络状态的,还能区分2G、3G、4G、LTE

    ,代码量也非常小,还很简单,而且可以通过苹果的审核。但是这种方法一定要保证statusbar没有被隐藏。因为当App隐藏了statusbar的时候,就不能获得网络状态。如iPhone X的statusbar就不包含网络这一标识,所以这个方法会出问题。

    使用Reachability获取网络状态

    1、首先你需要下载并导入Reachability。根据苹果官方演示demo,需把里面的Reachability文件拷贝到自己的工程。

    2、导入SystemConfiguration.framework框架。

    3、分析reachability中的代码含义,可以看到以下三种网络状态:无网络,wifi和蜂窝网。

    #pragma mark - 获取网络状态

    +(NSString *)internetStatus {

    Reachability *reachability= [Reachability reachabilityWithHostName:@"www.apple.com"];

    NetworkStatusinternetStatus= [reachability currentReachabilityStatus];

    NSString *net= @"wifi";

    switch (internetStatus) {

    case ReachableViaWiFi:

    net= @"wifi";

    break;

    case ReachableViaWWAN:

    net= @"wwan";

    break;

    case NotReachable:

    net= @"notReachable";

    default:

    break;

    }

    return net;

    }

    特别注意:HostName改成"www.baidu.com"或者其他中国网站时经常会获取网络状态错误,不能得到正确的网络状态。所以最好使用苹果的网站“www.apple.com“

    虽然这种方法比较权威,但是这种方法也存在着缺点,如不能知道用户使用的手机网络是2G、3G还是4G。

    具体代码如下:

    @interface AppDelegate ()

    @property (nonatomic) Reachability *reach;

    @end

    @implementation AppDelegate

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    //开启网络监听

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

    _reach = [Reachability reachabilityForInternetConnection];

    [_reach startNotifier];

    self.window = [[UIWindow alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];

    ViewController* vc = [[ViewController alloc]init];

    UINavigationController* nav = [[UINavigationController alloc]initWithRootViewController:vc];

    self.window.rootViewController = nav;

    [self.window makeKeyAndVisible];

    return YES;

    }

    - (void)networkChange:(NSNotification *)notification {

    Reachability *currReach = [notification object];

    NSParameterAssert([currReach isKindOfClass:[Reachability class]]);

    //对连接改变做出响应处理动作

    NetworkStatus status = [currReach currentReachabilityStatus];

    //如果没有连接到网络就弹出提醒实况

    if(status == NotReachable)

    {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络连接异常" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];

    [alert show];

    return;

    }

    if (status == ReachableViaWiFi || status == ReachableViaWWAN) {

    NSLog(@"网络连接正常");

    }

    }

    - (void)dealloc

    {

    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];

    }

    相关文章

      网友评论

          本文标题:iOS----获取当前网络状态

          本文链接:https://www.haomeiwen.com/subject/kpaubxtx.html