iOS 使用Reachability实时检测网络连接状况

当我们做项目的时候有的时候会去判断是否有网络从而在没网络时改为离线模式。

那么怎么进行网络判断呢,其实很简单我们只要使用Reachability类库就可以了,当然添加完Reachability类库之后我们要添加SystemConfiguration.framework

在 Reachability.h定义了三种网络状态:

   typedef enum {
        NotReachable = 0,            //无连接
        ReachableViaWiFi,            //使用3G/GPRS网络
        ReachableViaWWAN            //使用WiFi网络
    } NetworkStatus;

因此可以这样检查网络状态

Reachability *reach = [Reachability reachabilityWithHostname:@"www.apple.com"];
    switch ([reach currentReachabilityStatus])
    {
        case NotReachable:
        {
            isExistenceNetwork = NO;
            NSLog(@"没有网络");
        }
            break;
        case ReachableViaWiFi:
        {
            isExistenceNetwork = YES;
            NSLog(@"WiFi网络");
            [self versionUpgrade];
        }
            break;
        case ReachableViaWWAN:
        {
            isExistenceNetwork = YES;
            [self versionUpgrade];
            NSLog(@"3G网络");
        }
            break;
    }

好了,Reachability的基本用法介绍完了,那么言归正传怎么进行实时网络检测呢

一、 在程序的启动处开启通知

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //开启网络状况的监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    
    Reachability *hostReach = [Reachability reachabilityWithHostname:@"www.baidu.com"];
    [hostReach startNotifier];
    /*
     该方法在我查看的资料上是有调用的但是我使用的时候可能会有小的bug具体使用可以个人试试
     [self updateInterfaceWithReachability:hostReach];
     */

    return YES;
}

二、 连接改变

// 连接改变
- (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 == NotReachable) {  //没有连接到网络就弹出提实况
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提醒"
                                                        message:@"当前网络不好,请检查网络"
                                                       delegate:nil
                                              cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
    
}

 

posted @ 2014-12-17 15:13  暗夜追星  阅读(299)  评论(0编辑  收藏  举报