<span style="color: rgb(51, 51, 51); font-family: 宋体; font-size: 14px; text-indent: 28px; background-color: rgb(249, 249, 249);">手机开发的我们都知道,当前较大一部分的APP都利用到了网络但是如何能够给用户及时的提醒,在网络断开,或者网络状态发生改变的时候,这是一个值得深思的问题,有人说设置监视,每隔一段时间,扫描一下,当然可以,但是对于手机的各种资源来说,有点浪费。所以我们只用判定手机的网络状态是否发生改变,就可以了,改变时才启动相关的程序,这样是不是很好呢,所以下面为大家来分享一段代码,希望大家能够共同进步哦。</span>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window.rootViewController = [[LoginViewController alloc] init];
[self.window makeKeyAndVisible];
[self checkNetworkStates];
NSLog(@"网络状态码:----->%ld", [ALinNetworkTool getNetworkStates]);
return YES;
}
// 实时监控网络状态
- (void)checkNetworkStates
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkChange) name:kReachabilityChangedNotification object:nil];
_reacha = [Reachability reachabilityWithHostName:@"http://www.baidu.com"];
[_reacha startNotifier];
}
- (void)networkChange
{
NSString *tips;
NetworkStates currentStates = [ALinNetworkTool getNetworkStates];
if (currentStates == _preStatus) {
return;
}
_preStatus = currentStates;
switch (currentStates) {
case NetworkStatesNone:
tips = @"当前无网络, 请检查您的网络状态";
break;
case NetworkStates2G:
tips = @"切换到了2G网络";
break;
case NetworkStates3G:
tips = @"切换到了3G网络";
break;
case NetworkStates4G:
tips = @"切换到了4G网络";
break;
case NetworkStatesWIFI:
tips = nil;
break;
default:
break;
}
if (tips.length) {
[[[UIAlertView alloc] initWithTitle:@"i-流量" message:tips delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil, nil] show];
}
}