获得网络状态和实时监控网络状态改变

Apple 的 例程 Reachability 中介绍了取得/检测网络状态的方法。在你的程序中使用 Reachability 只须将该例程中的 Reachability.h 和 Reachability.m 拷贝到你的工程中。
Reachability 中定义了3种网络状态:

NotReachable

    无连接

ReachableViaCarrierDataNetwork (ReachableViaWWAN)

    使用3G/GPRS网络

ReachableViaWiFiNetwork (ReachableViaWiFi)

    使用WiFi网络

检测莫个特定站点的连接状况

    Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([r currentReachabilityStatus])
    {
        case NotReachable:
            // 没有网络连接
            break;
        case ReachableViaWWAN:
            // 使用3G网络
            break;
        case ReachableViaWiFi:
            // 使用WiFi网络
            break;
    }

检测当前网络环境

    // 是否wifi
    + (BOOL) IsEnableWIFI 
    {
        return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
    }

    // 是否3G
    + (BOOL) IsEnable3G 
    {
        return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
    }

连接状态实时通知

#import "AppDelegate.h"
#import "Reachability.h"

@interface AppDelegate ()

{
    Reachability *hostReach;
}

@end

@implementation AppDelegate



- (void)reachabilityChanged:(NSNotification *)note {
    Reachability *curReach = [note object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    NetworkStatus state = [curReach currentReachabilityStatus];

    if (state == NotReachable) {
        [self alertWithMessage:@"没有网络"];
    }else if (state == ReachableViaWiFi){
        [self alertWithMessage:@"wifi网络"];
    }else if (state == ReachableViaWWAN){
        [self alertWithMessage:@"移动网络"];
    }
}


- (void)alertWithMessage:(NSString *)message{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络状态" message:message delegate:nil cancelButtonTitle:@"YES" otherButtonTitles:nil, nil];
    [alert show];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 检测网络状态
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    [hostReach startNotifier];
    return YES;
}

我写的一个例子,给大家参考,希望对大家有所帮助
https://github.com/qcx123/NetworkMonitoring.git

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值