您的位置:首页 > 理论基础 > 计算机网络

检查网络状态—实时监测

2016-01-02 20:26 543 查看
//
//  ViewController.m
//  检查网络状态

/*
Reachability依赖于SystemConfiguration.framework这个框架
并且是非ARC的。所以需要在 Build Phases-Compile Soures-Reachability.m下
双击添加:-fno-objc-arc
*/

#import "ViewController.h"
#import "Reachability.h"
@interface ViewController ()
@property(nonatomic,strong) Reachability *conn;
@end

@implementation ViewController

- (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
{
//    NSLog(@"networkStateChange");
[self checkNetworkState];
}

/**
*  检测网络状态
*/
- (void)checkNetworkState
{
//1.检测WIFI状态
Reachability  *wifi = [Reachability reachabilityForLocalWiFi];

//2.检测手机是否能上网(wifi/3G/2.5G)
Reachability  *conn = [Reachability reachabilityForInternetConnection];

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

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: