iOS 网络状态监听和检查,

实现网络状态监听和监察网络状态,注意下面介绍两种方法都需要使用到第三方文件Reachability.h,和Reachability.m,这两个文件可以再第三方库ASIHttpRequest中得到,使用前引入头文件即可:

#import "Reachability.h"

1.实时监听,这个方法下会启动一个Run loop 实时监听网络的状态。注意这里将hostReach声明为一个全局的变量。

//开启网络状况的监听

-(void)giveNetNotification{

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

    hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];//可以以多种形式初始化

    [hostReach startNotifier];  //开始监听,会启动一个run loop

    [self updateInterfaceWithReachability: hostReach];

}

//监听到网络状态改变

- (void) reachabilityChanged: (NSNotification* )note{

    Reachability* curReach = [note object];

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

    [self updateInterfaceWithReachability: curReach];

}

//处理连接改变后的情况

- (void) updateInterfaceWithReachability: (Reachability*) curReach{

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

    NetworkStatus status = [curReach currentReachabilityStatus];

    if(status == ReachableViaWWAN){

        printf(" 3g/2G ");

    } else if(status == ReachableViaWiFi){

        printf(" wifi ");

    }else {

        printf(" 无网络 ");

    }

}

2.进行一次网络状态检查,这个方法不会时时触发,适用于检查连接到指定网络的状态;

-(void)netStatusNotification{

    if (([Reachability reachabilityForInternetConnection].currentReachabilityStatus==NotReachable)||([Reachability reachabilityForLocalWiFi].currentReachabilityStatus==NotReachable)){

        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"警告" message:@"您的设备暂时没有可用的网络,不能进行智能检点操作!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];

        [alert show];

    }

}

原文地址:https://www.cnblogs.com/longtaozi/p/3843743.html