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

93 网络状态监测

2015-09-06 11:56 561 查看
需要工程导入SystemConfiguration.framework
#import "Reachability.h"
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

//网络改变会发出通知
[[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];
}

// 用WIFI
// [wifi currentReachabilityStatus] != NotReachable
// [conn currentReachabilityStatus] != NotReachable

// 没有用WIFI, 只用了手机网络
// [wifi currentReachabilityStatus] == NotReachable
// [conn currentReachabilityStatus] != NotReachable

// 没有网络
// [wifi currentReachabilityStatus] == NotReachable
// [conn currentReachabilityStatus] == NotReachable

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{

}

- (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(@"没有网络");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: