Al03's blog

网络状态监控

不少网络应用对网络状态进行监控,主要是为了保护用户的流量。

网络 | 操作 ------------- | ------------- Wi-Fi | 高清图,数据同步等 移动网络 | 缩略图,停止后台数据网络同步 无网络 | 界面提醒,使用缓存

天猫

![](images/Image 2014-12-18 at 5.18.04 PM.png)

不过个人认为这种提示是多余的,每次网络变化都来个提示有点傻。而在移动网络观看视频或下载文件时提醒下也还可以(国内很多app都有,国外很少)。

检测网络

apple官方提供了一个Reachability的示例程序。

代码示例

- (void)viewDidLoad
{
    [super viewDidLoad];
    //注册网络监测通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange)                                                 name:kReachabilityChangedNotification object:nil];
    self.conn = [Reachability reachabilityForInternetConnection];
    [self.conn startNotifier];
}

- (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];

    // 3.判断网络状态
    if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
        NSLog(@"有wifi");

    } else if ([conn currentReachabilityStatus] != NotReachable) { // 没有使用wifi, 使用手机自带网络进行上网
        NSLog(@"使用手机自带网络进行上网");

    } else { // 没有网络

    NSLog(@"没有网络");
    }
}